8

I've had a set of data which I want to deal with. I was trying to run a python code to execute "awk" command in linux. hoverver no matter how I try different arguments or functions, it all didn't work.

there are two different way in which I have tried, but they all didn't work. I don't know why

1)

#!/usr/bin/env python
import subprocess as sp
cmd = "awk, '{print $2 '\t' $4 '\t' $5 '\t' $6}', B3LYPD.txt"
args = cmd.split(',')
p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE )

2)

#!/usr/bin/env python
import subprocess as sp
cmd = "awk, '{print $2 '\t' $4 '\t' $5 '\t' $6}'"
args = cmd.split(',')
p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE )
c = p.communicate('B3LYPD.txt')
print c
4
  • 1
    Use shlex.split not str.split. Commented Sep 1, 2013 at 10:50
  • 7
    If you are already programming in Python, are you sure you need to call awk? Python probably can do everything you need from awk just fine. Commented Sep 1, 2013 at 10:51
  • If you need a list of strings, rather than using c = "this, that, other" ; args = cmd.split(','), you can just use args = ["this", "that", "other"] and skip the split command. Commented Sep 1, 2013 at 13:23
  • Also, Lev's comment is right, you should be able to just read the text file line by line and use the split() function to pick out columns, if your code here is representative of your actual awk pattern. Commented Sep 1, 2013 at 13:25

2 Answers 2

7

While I agree that this is actually best done in Python, rather than invoking awk. If you really need to do this, then the actual error is with your awk.

#!/usr/bin/env python
import subprocess as sp
args = ["awk", r'{OFS="\t"; print $2,$4,$5,$6}', "B3LYPD.txt"]
p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE )
print(p.stdout.readline()) # will give you the first line of the awk output

Edit: Fixed missing quote.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use triple quotes to define the command and then shell=True in subprocess.

#!/usr/bin/env python
import subprocess as sp
cmd = """awk '{print $2"\t"$4"\t"$5"\t"$6}' B3LYPD.txt"""
p = sp.Popen(cmd, stdin=sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE,shell=True)
for l in p.stdout:
        print (l.decode())

Comments

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.