试图将bash语句转换为python中的子进程
作者:互联网
我试图将一个bash命令转换为python中的子进程. bash命令是:
cat LogFile.msg.log | grep ABCD | awk'{print $14,$10,$5,$7}’| sort -t” – k4 -n -r |头-10> output.csv
到目前为止,我有以下子进程:
cat = subprocess.Popen(['cat', 'LogFile.msg.log'],
stdout=subprocess.PIPE,
)
grep = subprocess.Popen(['grep', 'ABCD'],
stdin=cat.stdout,
stdout=subprocess.PIPE,
)
awk = subprocess.Popen(['awk', '{print $14,$10,$5,$7}'],
stdin=grep.stdout,
stdout=subprocess.PIPE,
)
sort = subprocess.Popen(['sort', '-t','' '', '-k4', '-n', '-r'],
stdin=awk.stdout,
stdout=subprocess.PIPE,
)
head = subprocess.Popen(['head', '-10'],
stdin=sort.stdout,
stdout=subprocess.PIPE,
)
out = subprocess.Popen(['>', 'output.csv'],
stdin=head.stdout,
stdout=subprocess.PIPE,
)
end_of_pipe = out.stdout
现在我收到以下错误:
Sort: empty tab
Traceback (most recent call last):
File "./latency2", line 39, in <module>
stdout=subprocess.PIPE,
File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我确定我错过了什么,但不确定是什么.
解决方法:
你有两个问题.第一个是你没有翻译参数来正确排序.运行此sort命令时:
sort -t' ' -k4 -n -r
shell将标记-t和”粘贴到单个参数“-t”(短划线,三通,空格)中.因此,它的正确子进程参数应该是:
sort = subprocess.Popen(['sort', '-t ', '-k4', '-n', '-r'],
stdin=awk.stdout,
stdout=subprocess.PIPE,
)
第二个问题是使用>最终重定向到文件. output.csv令牌.当shell看到这个时,它不会运行名为>的命令;相反,它打开文件output.csv进行写入,并将其设置为最后一个命令的标准输出句柄.因此,您不应该尝试运行名为>的命令.作为子过程;你需要通过打开一个文件来模拟shell:
head = subprocess.Popen(['head', '-10'],
stdin=sort.stdout,
stdout=open('output.csv', 'w'), # Not a pipe here
)
标签:pipeline,export-to-csv,python,output,subprocess 来源: https://codeday.me/bug/20190901/1780215.html