Python每日一练0024

发布时间:2019-06-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Python每日一练0024脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

问题

如何执行外部命令,如ls -l

解决方案

使用subPRocess

在Python 3.5之前,使用subprocess.call()函数

>>> import subprocess
>>> subprocess.call(['ls', '-l'])
total 4
drwxrwxr-x 4 root root 4096 Apr 18 02:46 test-rs
0

在Python3.5及之后,使用subprocess.run()函数

>>> import subprocess
>>> subprocess.run(['ls', '-l'])
total 4
drwxrwxr-x 4 root root 4096 Apr 18 02:46 test-rs
CompletedProcess(args=['ls', '-l'], returncode=0)

讨论

命令的执行默认不需要shell环境,所以当你使用ls -l作为参数时,需要将shell置位True,否则会报错误

>>> import subprocess
>>> subprocess.run('ls -l', shell=True)
total 4
drwxrwxr-x 4 root root 4096 Apr 18 02:46 test-rs
CompletedProcess(args=['ls', '-l'], returncode=0)

通常来说对于执行系统命令,我们会想到os.System,但在官方文档中已经建议了使用更高级的subprocess

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful reciPEs.

subprocess提供了更高级的用法,比如run可以指定stdinstdoutstderr,并且可以指定编码、超时时间等等选项,还可以获取到命令的返回结果

更多关于subprocess库见:https://docs.python.org/3/lib...

Stack Overflow

关注

欢迎关注我的微信公众号python每日一练

Python每日一练0024

脚本宝典总结

以上是脚本宝典为你收集整理的Python每日一练0024全部内容,希望文章能够帮你解决Python每日一练0024所遇到的问题。

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

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