繁体   English   中英

将结果从子流程传递到Unix排序

[英]Pipe result from subprocess to unix sort

我正在从python调用外部txt文件上的perl脚本,并将输出打印到outfile。 但是我想将输出传递给Unix的排序。 现在,我不是管道,而是先从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()

模拟外壳管道:

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

无需在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

只需使用bash。 使用python只会增加您不需要的复杂程度。

for file in $( ls); 
do 
    perl pydyn.pl $file | sort
done

上面是一个快速而肮脏的示例,在解析方面,以下是一个更好的选择:

ls | while read file; do perl pydyn.pl "$file" | sort; done

由于您在python中提出了问题,因此您也可以通过管道传递结果

p = subprocess.Popen("perl pydyn.pl %s | sort" % file, stdout=outfile,shell=True) 

但是为此,您必须将其设置为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.

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