subprocess模块

subprocess模块

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

import subprocess

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

    # 电脑操作系统编码为GBK
    success = cmd_obj.stdout.read().decode("GBK")
    error = cmd_obj.stderr.read().decode("GBK")
    print(success)
    print(error)

  执行结果:

posted @ 2020-10-19 19:12  chchcharlie、  阅读(114)  评论(0编辑  收藏  举报