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库
Thesubprocessmodule 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 thesubprocessdocumentation for some helpful recipes.
subprocess提供了更高级的用法,比如run可以指定stdin、stdout、stderr,并且可以指定编码、超时时间等等选项,还可以获取到命令的返回结果
更多关于subprocess库见:https://docs.python.org/3/lib...
来源
Stack Overflow
关注
欢迎关注我的微信公众号:python每日一练

相关推荐
赵家小少爷 2020-05-06
lhxxhl 2020-04-21
kkpiece 2020-03-03
skdzyl 2020-03-01
mieleizhi0 2020-03-01
猛禽的编程艺术 2020-02-02
Winterto0 2020-01-18
onetozero 2019-12-30
yuuuuy 2020-01-06
赵家小少爷 2019-12-09
Laozizuiku 2019-12-06
CloudXli 2019-12-05
jacktangj 2019-10-28
liusarazhang 2019-10-25
liusarazhang 2019-10-22
codeAB 2019-10-20
gnulinux 2019-06-05