如何从Python执行程序或调用系统命令 [英] How to execute a program or call a system command from Python

查看:40
本文介绍了如何从Python执行程序或调用系统命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python脚本中调用外部命令(就像我在Unix shell或Windows命令提示符下键入的一样)?

How do you call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?

推荐答案

使用 子过程 标准库中的模块:

Use the subprocess module in the standard library:

import subprocess
subprocess.run(["ls", "-l"])

subprocess.run os.system 上是更加灵活(您可以获取 stdout stderr 真实"状态代码,更好的是错误处理等).

The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...).

甚至 os.system 的文档建议改用 subprocess :

subprocess 模块提供了更强大的功能来生成新流程并检索其结果.使用该模块比使用此功能更可取.请参见用子流程模块替换旧功能部分.="https://docs.python.org/library/subprocess.html" rel ="noreferrer"> 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.

在Python 3.4和更早版本上,使用 subprocess.call 代替 .run :

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])

这篇关于如何从Python执行程序或调用系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆