代码示例
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
参考