简体   繁体   English

如何通过python代码执行awk命令

[英]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.我试图运行一个 python 代码来在 linux 中执行“awk”命令。 hoverver no matter how I try different arguments or functions, it all didn't work.无论我如何尝试不同的参数或函数,hoverver 都不起作用。

there are two different way in which I have tried, but they all didn't work.我尝试了两种不同的方法,但它们都不起作用。 I don't know why我不知道为什么

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

While I agree that this is actually best done in Python, rather than invoking awk.虽然我同意这实际上最好在 Python 中完成,而不是调用 awk。 If you really need to do this, then the actual error is with your awk.如果您真的需要这样做,那么实际的错误在于您的 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.编辑:修复丢失的报价。

You can use triple quotes to define the command and then shell=True in subprocess.您可以使用三引号来定义命令,然后在子进程中使用shell=True

#!/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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM