awk中的python变量 - python

我喜欢python,也喜欢awk,我知道可以通过子进程或命令库使用它,但是我想将awk与之前在python中定义的变量一起使用,例如以下简单示例:

file = 'file_i_want_read.list'

awk '{print $0}' file > another_file

有人知道我该怎么做或类似的东西吗?

python大神给出的解决方案

执行此操作的简单方法是不使用外壳程序,而只是将参数列表传递给subprocess,因此file只是这些参数之一。

唯一的窍门是,如果您不使用外壳程序,则不能使用外壳程序功能(如重定向)。您必须使用等效的subprocess功能。像这样:

with open('another_file', 'wb') as output:
    subprocess.check_call(['awk', '{print $0}', file], stdout=output)

如果确实要使用Shell重定向,则必须构建一个Shell命令行。这主要只是使用您喜欢的Python字符串操作方法的问题。但是您需要注意确保用引号和/或转义(例如,如果file可能是file i want read.list),那么除非您将其放在引号中,否则它将显示为4个单独的参数。 shlex.quote可以为您做到。所以:

cmdline = "awk '{print $0}' %s > another_file" % (shlex.quote(file),)
subprocess.check_call(cmdline, shell=True)