[英]How to execute a shell command through Python
I am new to Python programming. 我是Python编程的新手。 I want to execute a shell command "at" from a Python program. 我想从Python程序执行一个shell命令“at”。 Can any one of the Python gurus help me out? 任何一位Python专家都可以帮助我吗? Thanks in advance. 提前致谢。
The subprocess
module can be used for this purpose: subprocess
模块可用于此目的:
import subprocess
retcode = subprocess.call(["at", "x", "y", "z"])
Replace x
, y
and z
with the parameters to at
. 将x
, y
和z
替换为at
的参数。
Alternatively, rather than using subprocess.call(), you could use Popen to capture the output of the command (rather than the return code). 或者,您可以使用Popen捕获命令的输出(而不是返回代码),而不是使用subprocess.call()。
import subprocess
process = subprocess.Popen(['at','x','y','z'], stdout=subprocess.PIPE).communicate()[0]
This may not be relevant to the at command, but it is useful to know. 这可能与at命令无关,但知道它很有用。 The same can be done with the stdin and stderr. stdin和stderr也可以这样做。 Look at the documentation for more details. 查看文档以获取更多详细信息。
use search. 使用搜索。 already answered: How do I execute a program from python? 已经回答: 如何从python执行程序? os.system fails due to spaces in path 由于路径中的空格,os.system失败
subprocess.check_output
appears to be the canonical convenience function in Python 2.4+ for executing a command and inspecting the output. subprocess.check_output
似乎是Python 2.4+中用于执行命令和检查输出的规范便利函数。 It also raises an error if the command returns a non-zero value (indicating an error). 如果命令返回非零值(表示错误),它也会引发错误。
Like subprocess.call
, check_output
is a convenience wrapper around subprocess.Popen
, so you may prefer using Popen
directly. 像subprocess.call
, check_output
是围绕一个便利的包装subprocess.Popen
,所以你可能更喜欢使用Popen
直接。 But convenience wrappers are ...convenient, in theory. 但理论上,便利包装是......方便的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.