下面说了这么多,最有用的是这一句
status,output = subprocess.getstatusoutput(cmd)
代码
import subprocess import os cmd = "pwd" # 返回命令执行状态码,而将命令执行结果输出到屏幕 ret = os.system(cmd) print("system ret:", ret) """ /Users/myproject/mydemo/demo system ret: 0 """ # 可以获取命令执行结果,但是无法获取命令执行状态码 ret = os.popen(cmd) print("popen ret: ", ret.read()) """ popen ret: /Users/myproject/mydemo/demo """ ret = subprocess.run(cmd) print("run ret: ", ret.returncode) # run ret: 0 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) p.wait() print("Popen ret: ", p.stdout.read()) """ Popen ret: b'/Users/myproject/mydemo/demo\n' """ exitcode, output = subprocess.getstatusoutput(cmd) print("exitcode: ", exitcode) print("output: ", output) """ exitcode: 0 output: /Users/myproject/mydemo/demo """
写成一个函数
import subprocess class CommandException(Exception): pass def run_cmd(command): exitcode, output = subprocess.getstatusoutput(command) if exitcode != 0: raise CommandException(output) return output if __name__ == '__main__': cmd = "pwd" print("output: ", run_cmd(cmd)) # output: /Users/myproject/mydemo/demo
函数 说明
os.system(command) 返回状态码,执行结果输出到屏幕
os.popen(command).read() 返回执行结果,没有状态码
– –
subprocess.run() Python 3.5中新增的函数。执行指定的命令,等待命令执行完成后返回一个包含执行结果的CompletedProcess类的实例
subprocess.call() 执行指定的命令,返回命令执行状态,其功能类似于os.system(cmd)
subprocess.check_call() Python 2.5中新增的函数。 执行指定的命令,如果执行成功则返回状态码,否则抛出异常。其功能等价于subprocess.run(…, check=True)
subprocess.check_output() Python 2.7中新增的的函数。执行指定的命令,如果执行状态码为0则返回命令执行结果,否则抛出异常
subprocess.getoutput(cmd) 接收字符串格式的命令,执行命令并返回执行结果,其功能类似于os.popen(cmd).read()和commands.getoutput(cmd)
subprocess.getstatusoutput(cmd) 执行cmd命令,返回一个元组(命令执行状态, 命令执行结果输出)
https://blog.csdn.net/mouday/article/details/86367256