带有awk和管道的Python子流程
我的Python脚本中有以下语句:带有awk和管道的Python子流程,python,bash,awk,subprocess,Python,Bash,Awk,Subprocess,我的Python脚本中有以下语句: year = '1966' file = 'test.txt' cmd = "awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc" % (year, file) bla = run_command(cmd) 其中fun\u command()是函数: def run_command(command): pr
year = '1966'
file = 'test.txt'
cmd = "awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc" % (year, file)
bla = run_command(cmd)
其中fun\u command()
是函数:
def run_command(command):
process = subprocess.Popen([sys.executable, command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = process.wait()
if retcode != 0:
raise Exception, "Problem running command: " + command
stdout, stderr = process.communicate()
return stdout
产生以下输出:
TypeError: unsupported operand type(s) for |: 'str' and 'str'
有什么问题吗?“awk'{FS=“|”}{if($2==%s)print$1}'%s | sort-n | uniq | wc”
在这里,您需要转义内部
“|”
“awk'{FS=\“\\\”}{if($2==%s)print$1}'%s | sort-n | uniq | wc'
sys.executable
是当前运行的Python解释器,因此您试图以Python代码的形式执行shell代码。只用
def run_command(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = process.wait()
if retcode != 0:
raise Exception, "Problem running command: " + command
stdout, stderr = process.communicate()
return stdout
我不得不说,从
python
调用awk
就像(错误地引用拉里·沃尔的话)拥有一把Uzi机枪,然后用它击中某人的头部。知道吗,但我(仅)将它用于原型制作。将列表和shell=True
结合起来通常是个坏主意。但是,sys.executable
是正在运行的Python解释器,而不是shell解释器。请改用Popen(command,shell=True,…)
。了解返回空字符串(即b''
)的原因。我在shell中测试了该命令,它工作正常。wait()
等待进程终止communicate()
与进程交互,但在等待之后,进程已经终止。检查管道是否仍然有效。