Reputation: 3849
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?
Upvotes: 2
Views: 1501
Reputation: 531888
sys.executable
is the Python interpreter currently running, so you are trying to execute your shell code as Python code. Just use
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
Upvotes: 1
Reputation: 5675
"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"
Upvotes: 3