Python 系统命令调用

发布时间:2019-06-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Python 系统命令调用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

脚本宝典总结

以上是脚本宝典为你收集整理的Python 系统命令调用全部内容,希望文章能够帮你解决Python 系统命令调用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。