subprocess

subprocess模块

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

import subprocess
while True:
    #输入终端命令
    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(sucess,'正确的结果')
	error = obj.stderr.read().decode('gbk')
    if error:
        print(error,'错误的结果')
原文地址:https://www.cnblogs.com/littleb/p/11892278.html