13

I need to write a python script where I need to call a few awk commands inside of it.

#!/usr/bin/python
import os, sys
input_dir = '/home/abc/data'

os.chdir(input_dir)
#wd=os.getcwd()
#print wd
os.system ("tail -n+2 ./*/*.tsv|cat|awk 'BEGIN{FS="\t"};{split($10,arr,"-")}{print arr[1]}'|sort|uniq -c")

It gives an error in line 8: SyntaxError: unexpected character after line continuation character

Is there a way I can get the awk command get to work within the python script? Thanks

2
  • escape the quotes around \t? Commented May 21, 2013 at 16:42
  • 2
    Why? there is nothing sed/awk/sort/uniq can do that you cannot do directly from within python and as a bonus you get a solution that runs on all platform python is ported to! Commented May 21, 2013 at 19:19

2 Answers 2

14

You have both types of quotes in that string, so use triple quotes around the whole thing

>>> x = '''tail -n+2 ./*/*.tsv|cat|awk 'BEGIN{FS="\t"};{split($10,arr,"-")}{print arr[1]}'|sort|uniq -c'''
>>> x
'tail -n+2 ./*/*.tsv|cat|awk \'BEGIN{FS="\t"};{split($10,arr,"-")}{print arr[1]}\'|sort|uniq -c'
Sign up to request clarification or add additional context in comments.

1 Comment

stack overflow doesn't format it correctly in the code blocks, but if you copy paste the line into the interpreter you'll see what I mean.
9

You should use subprocess instead of os.system:

import subprocess
COMMAND = "tail -n+2 ./*/*.tsv|cat|awk 'BEGIN{FS=\"\t\"};{split($10,arr,\"-\")}{print arr[1]}'|sort|uniq -c"  

subprocess.call(COMMAND, shell=True)

As TehTris has pointed out, the arrangement of quotes in the question breaks the command string into multiple strings. Pre-formatting the command and escaping the double-quotes fixes this.

2 Comments

Adding even more |cats to the pipeline would make it even better, no?
Why should he use subprocess instead of os.system? Thanks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.