Subprocess模块
import subprocess
def run():
result = subprocess.run(["df", "-h"], shell=True)
print(result) # 返回值为CompletedProcess类的实例化对象:CompletedProcess(args=['df', '-h'], returncode=0)
def call():
result = subprocess.call(["ls", "-l"], shell=True)
print(result) # 返回值为命令执行状态,0或非0
def check_call():
result = subprocess.check_call(["ls", "-l"], shell=True)
print(result) # 命令执行成功返回值为0,执行错误抛出异常
def getstatusoutput():
result = subprocess.getstatusoutput("df -h") # 接受字符串形式的命令
print(result) # 返回值为一个元组,第一个元素为命令执行状态,第二个元素为执行结果
def getoutput():
subprocess.getoutput("df -h") # 接受字符串形式的命令,直接打印出结果
def check_output():
result = subprocess.check_output("df -h", shell=True)
print(result) # 返回值为命令执行结果
def popen():
result = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result) # 返回值为一个Popen对象
print(result.stdout.read()) # 标准输出,含有命令执行结果
print(result.stderr.read()) # 错误输出,含有报错信息,如果不报错为空
# subprocess.PIPE 是一个管道,负责收集命令的执行结果