subprocess模块

南笙酒味 提交于 2019-12-05 00:34:35

ubprocess模块

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

 

'''
subprocess:
    sub: 子
    process: 进程
'''

import subprocess
while True:
    # 1.让用户输入终端命令
    cmd_str = input('请输入终端命令:').strip()
    # Popen(cmd命令, shell=True,
    # stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # 调用Popen就会将用户的终端命令发送给本地操作系统的终端
    # 得到一个对象,对象中包含着正确或错误的结果。
    obj = subprocess.Popen(
        cmd_str, shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    success = obj.stdout.read().decode('gbk')
    if success:
        print(success, '正确的结果')

    error = obj.stderr.read().decode('gbk')
    if error:
        print(error, '错误的结果')

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!