subprocess模块

通过标准库中的subprocess包来分支一个子进程,并运行一个外部的程序。

subprocess.Popen() 调用系统命令
subprocess.getoutput() 执行linux命令,返回命令结果

import subprocess

# Popen
res = subprocess.Popen('pwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  # stdout接收命令结果,stderr接收错误结果
cmd = res.stdout.read()  # 读取输出
err_msg = res.stderr.read()  # 若命令返回结果有错误
print(cmd.decode('utf8'))
print(err_msg.decode('utf8'))

# getoutput
result = subprocess.getoutput('pwd')
print(result)

原文地址:https://www.cnblogs.com/sunqim16/p/6803034.html