Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有awk和管道的Python子流程_Python_Bash_Awk_Subprocess - Fatal编程技术网

带有awk和管道的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

我的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):                                     
  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()
与进程交互,但在等待之后,进程已经终止。检查管道是否仍然有效。