使用 awk 和管道的 Python 子进程

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

有什么问题吗?

最佳答案

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

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

关于使用 awk 和管道的 Python 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286091/

相关文章:

python - 使用 sed、awk、perl 等删除 N 个匹配模式

python - “列表”对象没有属性 'find'

Python - 从字符串中删除前 5 个字符 - 如何获取新的较短字符串?

bash - 通过 bash 脚本从 'time' 命令获取值

bash - at命令未执行

bash - 如何在 awk 中匹配连字符 (-) 和井号 (#)?

python - Blob.generate_signed_url() 未能出现 AttributeError

python - PYQT - 帮助分析 python 代码{内置方法 exec_}

linux - 如何让 `find` 忽略 .svn 目录?

bash - 流过滤大量由标准输入中的行号指定的行