簡體   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