Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute awk command by python code

Tags:

python

linux

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
like image 761
user1971989 Avatar asked Sep 01 '13 10:09

user1971989


2 Answers

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.

like image 165
user2736953 Avatar answered Oct 29 '22 04:10

user2736953


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())
like image 1
CodeCode Avatar answered Oct 29 '22 05:10

CodeCode