脚本宝典收集整理的这篇文章主要介绍了Python每日一练0024,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
问题
如何执行外部命令,如ls -l
解决方案
在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
可以指定stdin
、stdout
、stderr
,并且可以指定编码、超时时间等等选项,还可以获取到命令的返回结果
更多关于subprocess
库见:https://docs.python.org/3/lib...
来源
Stack Overflow
关注
以上是脚本宝典为你收集整理的Python每日一练0024全部内容,希望文章能够帮你解决Python每日一练0024所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。