我的 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/