如何调用外部命令? [英] How to call an external command?

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

问题描述

如何在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 模块:

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

子流程系统的优势更加灵活(您可以获取 stdout stderr , 状态代码,更好的错误处理等)。

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

官方文档建议使用子流程模块,而不是可选的 os.system()

The official documentation recommends the subprocess module over the alternative os.system():


子进程模块提供了更强大的生成工具新流程和检索他们的结果;使用该模块优于使用此功能[ os.system () ]。

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function [os.system()].

中的python.org/library/subprocess.html#replacing-older-functions-with-the-subprocess-module rel = noreferrer>用子流程模块替换旧功能子过程文档可能有一些有用的食谱。

The Replacing Older Functions with the subprocess Module section in the subprocess documentation may have some helpful recipes.

对于3.5之前的Python版本,请使用 call

For versions of Python before 3.5, use call:

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

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

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