subprocess模块

subprocess模块

可以通过python代码给操作系统终端发送命令,并可以返回结果

sub:子

process:进程

import subprocess
while True:
    # 1、让用户输入终端命令
    cmd_str = input('请输入终端命令:')
    # 2、调用subprocess中.Popen(命令, shell=True, stdout=subprocess.PIPE, sdterr=subprocess.PIPE)得到一个对象
    obj = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # 3、获取成功时的返回值
    success = obj.stdout.read().decode('gbk')
    if success:
        print(success)
    # 4、获取失败时的返回值
    error = obj.stderr.read().decode('gbk')
    if error:
        print(error)
posted @ 2019-11-19 18:53  Mr沈  阅读(145)  评论(0编辑  收藏  举报