Python 系统命令调用之 subprocess

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

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

Popen

# 标准用法使用数据传参,可以用shlex库来正确切割命令字符串
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
import subprocess
try:
    proc = subprocess.Popen([`ls`, `-a`, `/`], stdout=subprocess.PIPE)
    print(proc.stdout.read())  
except:
    print("error when run `ls` command")
# 使用with语句替代try-except-finally
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
# Windows下由于Windows API的CreateProcess()入参为字符串,
# Popen需要把输入的数组拼接为字符串。因此建议直接传入字符串参数。
p = subprocess.Popen('D:\\Tools\\Git\\git-bash.exe --cd="D:\\Codes"', stdout=subprocess.PIPE)
print(p.stdout.read())

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官方文档:

猜你喜欢

转载自blog.csdn.net/P_Core_996/article/details/104774814