[英]Pipe result from subprocess to unix sort
I am calling a perl script on an external txt files from python, and printing the output to an outfile. 我正在从python调用外部txt文件上的perl脚本,并将输出打印到outfile。 But instead I want to pipe the output to unix's sort.
但是我想将输出传递给Unix的排序。 Right now I am not piping, but are writing the output from the perl program first, then doing by combining my code under, and this stackoverflow answer .
现在,我不是管道,而是先从perl程序编写输出,然后通过将我的代码与下面的stackoverflow答案结合起来进行操作。
import subprocess
import sys
import os
for file in os.listdir("."):
with open(file + ".out", 'w') as outfile:
p = subprocess.Popen(["perl", "pydyn.pl", file], stdout=outfile)
p.wait()
To emulate the shell pipeline: 模拟外壳管道:
#!/usr/bin/env python
import pipes
import subprocess
pipeline = "perl pydyn.pl {f} | sort >{f}.out".format(f=pipes.quote(filename))
subprocess.check_call(pipeline, shell=True)
without invoking the shell in Python: 无需在Python中调用Shell:
#!/usr/bin/env python
from subprocess import Popen, PIPE
perl = Popen(['perl', 'pydyn.pl', filename], stdout=PIPE)
with perl.stdout, open(filename+'.out', 'wb', 0) as outfile:
sort = Popen(['sort'], stdin=perl.stdout, stdout=outfile)
perl.wait() # wait for perl to finish
rc = sort.wait() # wait for `sort`, get exit status
Just use bash. 只需使用bash。 Using python just adds a level of complexity you don't need.
使用python只会增加您不需要的复杂程度。
for file in $( ls);
do
perl pydyn.pl $file | sort
done
Above is a quick and dirty example, a better alternative in terms of parsing is the following: 上面是一个快速而肮脏的示例,在解析方面,以下是一个更好的选择:
ls | while read file; do perl pydyn.pl "$file" | sort; done
Since you asked the question in python you can also pipe the result 由于您在python中提出了问题,因此您也可以通过管道传递结果
p = subprocess.Popen("perl pydyn.pl %s | sort" % file, stdout=outfile,shell=True)
but for this you're gonna have to make it shell=True
which is not a good practice 但是为此,您必须将其设置为
shell=True
,这不是一个好习惯
Here's one way without making it shell=True
这是不将其设置为
shell=True
的一种方法
p = subprocess.Popen(["perl", "pydyn.pl", file], stdout=subprocess.PIPE)
output = subprocess.check_output(['sort'], stdin=p.stdout,stdout=outfile)
p.wait()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.