[英]python subprocess.Popen vs os.popen
I'm trying to get the output of the following shell command in my python script, 我试图在我的python脚本中获取以下shell命令的输出,
hadoop fs -ls /projectpath/ | grep ^d | grep -v done | head -1 | awk {'print $8'}
I can successfully get the output through os.popen
as follows: 我可以通过
os.popen
成功获取输出,如下所示:
import os
cmd = "hadoop fs -ls /projectpath/ | grep ^d | grep -v done | head -1 | awk {'print $8'}"
p = os.popen(cmd,"r")
while 1:
line = p.readline()
if not line: break
print line
But os.popen()
is deprecated since python 2.6 so I wanted to replace the above snippet with the subprocess.Popen()
function. 但是从python 2.6开始不推荐使用
os.popen()
所以我想用os.popen()
subprocess.Popen()
函数替换上面的代码片段。
But the code snippet for subprocess.Popen()
below gives a different result than the code snippet above. 但是下面的
subprocess.Popen()
的代码片段给出了与上面的代码片段不同的结果。
import subprocess as sub
import shlex
cmd = "hadoop fs -ls /projectpath/ | grep ^d | grep -v done | head -1 | awk {'print $8'}"
args = shlex.split(cmd)
p = sub.Popen(args,stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output
The above command just gives output for 'hadoop fs -ls /projectpath/'
part of the command. 上面的命令只为命令的
'hadoop fs -ls /projectpath/'
提供输出。 I have tried consulting several references ( http://docs.python.org/2/library/subprocess.html#popen-objects , Python, os.system for command-line call (linux) not returning what it should? ) for subpocess.Popen()
but cannot get it to execute the command in the string cmd. 我试过咨询几个引用( http://docs.python.org/2/library/subprocess.html#popen-objects,Python,os.system 用于命令行调用(linux)不返回它应该的内容? )for
subpocess.Popen()
但无法让它在字符串cmd中执行命令。 Can anyone point out what I'm doing wrong? 谁能指出我做错了什么?
try this: 尝试这个:
cmd = "hadoop fs -ls /projectpath/ | grep ^d | grep -v done | head -1 | awk {'print $8'}"
p = sub.Popen(cmd,stdout=sub.PIPE,stderr=sub.PIPE, shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.