在一个Python 2.4脚本中,我想执行一个os系统调用`ls -l`或`curl`,例如在一个变量中捕获输出。怎么办? [英] In a Python 2.4 script, I would like to execute a os system call `ls -l` or `curl` for example and capture the output in a variable. How to do this?
问题描述
在脚本中,我想发出如
curl -XPUT'http:// somerul / _search'-d file.txt
或 ls -ltrh
并将这些命令的输出捕获到变量中。对于curl命令,输出将是一个我将解析的json格式(请指出,如果一个旧的json解析器可供我使用).. 我如何在python脚本中进行这些系统调用,并将输出捕获到变量中?
提前谢谢!
您不能直接用 os.system
或 os
。由于文档 *告诉你,它只是执行命令一个子壳。命令的stdout将是shell的stdout,这是你的标准输出,所以没有什么可以做的来捕获它。
这就是为什么文档明确地告诉你使用 subprocess
。而且,如果你阅读了文档,那么在使用子进程
模块替换旧的函数。其中包括你正在试图做的第一个例子。
不幸的是,你真正想要的是 check_output
,这是不幸的是2.7+。如果你这样做,那就是:
out = subprocess.check_output(['ls','-ltrh'] )
获取它的最简单的方法是安装来自PyPI的 subprocess32
,它将所有内容从Python 3.2的子进程
模块到2.4-2.7。
如果你想坚持使用stdlib,可以从 2.7来源查看,这是一个微不足道的函数写在2.4中已经存在的部分上:
def check_output(* popenargs,** kwargs):
如果在kwargs中的'stdout':
raise ValueError('stdout参数不允许,它将被覆盖')
process = Popen(stdout = PIPE,* popenargs,** kwargs)
输出,unused_err = process.communicate()
retcode = proc ess.poll()
如果代码:
cmd = kwargs.get(args)
如果cmd为None:
cmd = popenargs [0]
raise CalledProcessError(retcode,cmd,output = output)
返回输出
或者,如果你只是想要这样做一次,你不需要包装器:
p = subprocess.Popen(cmd,stdout = subprocess .PIPE)
out,_ = p.communicate()
do_something_with(out)
有关JSON解析器的附加问题:
simplejson
是成为stdlib的解析器 json
module in 2.6。最新版本仅适用于2.5+以上旧版本(相信3.0之前的所有内容,但不要引用我)为2.4 +。
*请注意,我链接到2.7,因为2.4更难在网上找到。但是他们没有从2.4 $和2.7之间的 os.system
或 subprocess
中删除任何功能,添加或更改了哪些新功能。
I am writing a python script on a remote server with an old version of python 2.4.
In the script I want to issue commands like curl -XPUT 'http://somerul/_search' -d file.txt
or an ls -ltrh
and capture the outputs of these commands into a variable. For the curl command the output will be a json format that I will parse (please advise if an old json parser is available for me to use)..
How can I make these kinds of system calls in the python script and capture the output into a variable?
Thank you in advance!
You can't do it directly with os.system
or anything else in os
. As the documentation* tells you, it just executes the command in a subshell. The command's stdout will be the shell's stdout which is your stdout, so there's nothing you can do to capture it.
That's why the docs explicitly tell you to use subprocess
instead. And, if you read the docs, there's a nice section on Replacing Older Functions with the subprocess
Module. Which includes exactly what you're trying to do as the first example.
Unfortunately, what you really want here is check_output
, which is unfortunately 2.7+. If you had that, it would just be:
out = subprocess.check_output(['ls', '-ltrh'])
The simplest way to get it is to install subprocess32
from PyPI, which backports everything from Python 3.2's subprocess
module to 2.4-2.7.
If you want to stick with the stdlib, as you can see from the 2.7 source, this is a trivial function to write on top of pieces that were already there in 2.4:
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
Or, if you just want to do this one time, you don't need the wrapper:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, _ = p.communicate()
do_something_with(out)
For your parenthetical extra question about a JSON parser:
simplejson
is the parser that became the stdlib json
module in 2.6. The latest versions only work with 2.5+, but older versions (I believe everything before 3.0, but don't quote me on that) were for 2.4+.
* Note that I linked to 2.7, because 2.4 is harder to find online. But they didn't remove any features from os.system
or subprocess
between 2.4 and 2.7, and they do carefully note what new features were added or changed.
这篇关于在一个Python 2.4脚本中,我想执行一个os系统调用`ls -l`或`curl`,例如在一个变量中捕获输出。怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!