subprocess模块

subprocess模块

能够经过python代码给操做系统终端发送命令,并能够返回结果python

sub:子shell

process:进程操作系统

import subprocess
while True:
    # 一、让用户输入终端命令
    cmd_str = input('请输入终端命令:')
    # 二、调用subprocess中.Popen(命令, shell=True, stdout=subprocess.PIPE, sdterr=subprocess.PIPE)获得一个对象
    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)
相关文章
相关标签/搜索