带有awk和管道的Python子进程

时间:2016-10-27 13:39:35

标签: 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_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'

任何想法有什么不对?

2 个答案:

答案 0 :(得分:3)

"awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"
在这里你需要逃避内部"|"

"awk '{FS=\"|\"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"

答案 1 :(得分:1)

sys.executable是当前正在运行的 Python 解释器,因此您尝试将您的shell代码作为Python代码执行。只需使用

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