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

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

问题描述

如何从 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?

推荐答案

使用 subprocess 标准库中的模块:

Use the subprocess module in the standard library:

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

subprocess.run 超过 os.system 是它更灵活(你可以得到 stdout, stderr,真实"状态代码,更好错误处理 等...).

甚至 os.system 的文档a> 推荐使用 subprocess 代替:

Even the documentation for os.system recommends using subprocess instead:

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"])

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

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