如何执行外部命令,如ls -l
html
使用subprocess
库python
在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
库函数
Thesubprocess
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 thesubprocess
documentation for some helpful recipes.
subprocess
提供了更高级的用法,好比run
能够指定stdin
、stdout
、stderr
,而且能够指定编码、超时时间等等选项,还能够获取到命令的返回结果this
更多关于subprocess
库见:https://docs.python.org/3/lib...编码
Stack Overflowspa
欢迎关注个人微信公众号:python每日一练code