2

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
xgdgsc
1,3671 gold badge13 silver badges44 bronze badges
asked Jan 1, 2016 at 14:27
1
  • 1
    Look at the syntax highlighting in your question's code. Commented Jan 1, 2016 at 14:33

1 Answer 1

2

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.

answered Jan 1, 2016 at 14:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.