user1971989
user1971989

Reputation: 121

How to execute awk command by python code

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

Upvotes: 8

Views: 18979

Answers (2)

CodeCode
CodeCode

Reputation: 41

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())

Upvotes: 2

user2736953
user2736953

Reputation: 156

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.

Upvotes: 7

Related Questions