Andrej Andrej - 1 month ago 28
Python Question

Python subprocess with awk and pipes

I have the following statements in my Python script:

year = '1966'
file = 'test.txt'
cmd = "awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc" % (year, file)
bla = run_command(cmd)


where
fun_command()
is the function:

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


The following output is produced:

TypeError: unsupported operand type(s) for |: 'str' and 'str'


Any ideas what is wrong?

Answer

"awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"
Here you need to escape inner "|"

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

Comments