将结果从子流程传递到Unix排序 [英] Pipe result from subprocess to unix sort

查看:108
本文介绍了将结果从子流程传递到Unix排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从python调用外部txt文件上的perl脚本,并将输出打印到outfile.但是我想将输出传递给Unix的排序.现在,我不是管道,而是先从perl程序编写输出,然后通过组合下面的代码和此stackoverflow答案来完成此操作.

I am calling a perl script on an external txt files from python, and printing the output to an outfile. But instead I want to pipe the output to unix's sort. 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.

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

推荐答案

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

Since you asked the question in python you can also pipe the result

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

但是为此,您必须将其设置为shell=True,这不是一个好习惯

but for this you're gonna have to make it shell=True which is not a good practice

这是不将其设为shell=True

  p = subprocess.Popen(["perl", "pydyn.pl", file], stdout=subprocess.PIPE)
  output = subprocess.check_output(['sort'], stdin=p.stdout,stdout=outfile)
  p.wait()

这篇关于将结果从子流程传递到Unix排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆