Python系统命令调用

前言

Python 3不再推荐使用老的os.system()os.popen()commands.getstatusoutput()等方法来调用系统命令,而建议统一使用subprocess库所对应的方法如:Popen()getstatusoutput()call()

推荐并记录一些常用的使用范例:

Popen

import subprocess

try:

     proc = subprocess.Popen([ls, -a, /], stdout=subprocess.PIPE)

     print(proc.stdout.read())

except:

     print(“error when run ls command”)

call

import subprocess

try:

     retcode = subprocess.call(“mycmd” + “ myarg”, shell=True)
     if retcode < 0:

     print(“Child was terminated by signal”, -retcode, file=sys.stderr)

     else:

     print(“Child returned”, retcode, file=sys.stderr)

except OSError as e:

     print(“Execution failed:”, e, file=sys.stderr)

getstatusoutput/getoutput

  >>> subprocess.getstatusoutput(‘ls /bin/ls’)

(0, ‘/bin/ls’)

 >>> subprocess.getoutput(‘ls /bin/ls’)

‘/bin/ls’

详细可以查阅Python 3官方文档: