在 Python 2.5 及更低版本上创建不使用 shell 的可执行进程
正如标题所说:
- 不能使用
subprocess
模块,因为它应该在 2.4 和 2.5 上工作, - 不应生成 Shell 进程来传递参数。
为了解释 (2),请考虑以下代码:
>>> x=os.system('foo arg')
sh: foo: not found
>>> x=os.popen('foo arg')
sh: foo: not found
>>>
如您所见,os.system
和 os.popen
通过系统 shell 运行给定的命令(“foo”)( “嘘”)。我不希望这种情况发生(否则,丑陋的“未找到”消息会在不受我控制的情况下打印到程序 stderr)。
最后,我应该能够向该程序传递参数(上面示例中的“arg”)。
在 Python 2.5 和 2.4 中如何实现这一点呢?
Just what the title says:
- The
subprocess
module cannot be used as this should work on 2.4 and 2.5 - Shell process should not be spawned to pass arguments.
To explain (2), consider the following code:
>>> x=os.system('foo arg')
sh: foo: not found
>>> x=os.popen('foo arg')
sh: foo: not found
>>>
As you can see os.system
and os.popen
runs the given command ("foo") via a system shell ("sh"). I don't want this to happen (otherwise, ugly 'not found' messages are printed to program stderr without my control).
Finally, I should be able to pass arguments to this program ('arg' in the above example).
How would one go about doing this in Python 2.5 and 2.4?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要使用 Python 2.4 中提供的 subprocess 模块,
您将需要包含完整路径,因为您没有使用 shell。
http://docs.python.org/library/subprocess.html#替换-os-system
或者,您也可以将 subprocess.PIPE 传递给 stderr 和 stdout 以抑制消息。请参阅上面的链接了解更多详细信息。
You probably need to use the subprocess module which is available in Python 2.4
You will need to include the full path since you aren't using the shell.
http://docs.python.org/library/subprocess.html#replacing-os-system
Alternatively you can also pass subprocess.PIPE to the stderr and stdout to suppress the messages. See the link above for more details.
如前所述,您可以(并且应该)使用 subprocess 模块。
默认情况下,
shell
参数为False
。这很好,而且很安全。此外,您不需要传递完整路径,只需将可执行文件名称和参数作为序列(元组或列表)传递即可。您还可以使用 subprocess 模块中已定义的这两个便利函数:
记住您可以将
stdout
和/或stderr
重定向到PIPE
,因此它不会打印到屏幕上(但输出仍然可供你的 python 程序读取)。默认情况下,stdout
和stderr
都是None
,这意味着无重定向,这意味着它们将使用相同的内容stdout/stderr 作为你的 python 程序。另外,您可以使用
shell=True
并将stdout
.stderr
重定向到 PIPE,这样就不会打印任何消息:As previously described, you can (and should) use the subprocess module.
By default,
shell
parameter isFalse
. This is good, and quite safe. Also, you don't need to pass the full path, just pass the executable name and the arguments as a sequence (tuple or list).You can also use these two convenience functions already defined in subprocess module:
Remember you can redirect
stdout
and/orstderr
toPIPE
, and thus it won't be printed to the screen (but the output is still available for reading by your python program). By default,stdout
andstderr
are bothNone
, which means no redirection, which means they will use the same stdout/stderr as your python program.Also, you can use
shell=True
and redirect thestdout
.stderr
to a PIPE, and thus no message will be printed: