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, '错误的结果')