Python每日一练0024

问题

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

解决方案

使用subprocesspython

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

>>> 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,不然会报错误ide

>>> 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,而且能够指定编码、超时时间等等选项,还能够获取到命令的返回结果this

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

来源

Stack Overflowspa

关注

欢迎关注个人微信公众号:python每日一练code

相关文章
相关标签/搜索