user3580316
user3580316

Reputation:

Python subprocess invalid syntax

I am trying to run a long bash-command in a subprocess, but it's giving me syntax error. The goal is to add the filename in the end of the command.

ok="file.csv"

p = subprocess.Popen("awk -F'"?,"?' '{ split($2, a, / /); if (a[2] == "KB") a[1] /= 1000; sum += a[1] } END { print sum }' %s " %(ok),stdout=subprocess.PIPE, shell=True)
(sum,err) = p.communicate()

print sum

This is how I run the code in command-line (which works):

student@student-vm:~/Downloads$ awk -F'"?,"?' '{ split($2, a, / /); if (a[2] == "KB") a[1] /= 1000; sum += a[1] } END { print sum }' file.csv
1346.94

Upvotes: 2

Views: 1843

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49330

Look at the syntax highlighting. Do you see how the string you're sending to Popen() isn't a single string? There's a string, then ?,, then a string, then KB, then a string. Try using a triple-quoted string:

ok="file.csv"

p = subprocess.Popen("""awk -F'"?,"?' '{ split($2, a, / /); if (a[2] == "KB") a[1] /= 1000; sum += a[1] } END { print sum }' %s """ %(ok),stdout=subprocess.PIPE, shell=True)
(sum,err) = p.communicate()

print sum

Note that the syntax highlighting in this answer's code makes it look like it's still broken, but that's an issue with how it handles triple-quoted strings. Put it into an IDE or editor like Notepad++ and you'll see that it's recognized and displayed as a single string.

Upvotes: 2

Related Questions