【问题标题】:Figuring out pipes in python在python中找出管道
【发布时间】:2015-01-09 14:03:47
【问题描述】:

我目前正在用 python 编写一个程序,但我被卡住了。所以我的问题是: 我有一个程序可以读取文件并将一些行打印到标准输出,如下所示:

#imports
import sys

#number of args
numArgs = len(sys.argv)

#ERROR if not enough args were committed
if numArgs <= 1:
    sys.exit("Not enough arguments!")

#naming input file from args
Input = sys.argv[1]

#opening files
try:
    fastQ = open(Input , 'r')
except IOError, e:
    sys.exit(e)

#parsing through file
while 1:

    #saving the lines
    firstL = fastQ.readline()
    secondL = fastQ.readline()

    #you could maybe skip these  lines to save ram
    fastQ.readline()
    fastQ.readline()

    #make sure that there are no blank lines in the file
    if firstL == "" or  secondL == "":
        break

    #edit the Header to begin with '>'
    firstL = '>' + firstL.replace('@' , '')

    sys.stdout.write(firstL)
    sys.stdout.write(secondL)

#close both files
fastQ.close()

现在我想重写这个程序,这样我就可以运行如下命令行:zcat "textfile" |蟒蛇“我的程序”>“其他文件”。所以我环顾四周,找到了子进程,但似乎不知道该怎么做。感谢您的帮助

编辑:

现在,如果您正在尝试编写 Python 脚本来协调 zcat 和 myprogram 的执行,那么您可能需要 subprocess. – rchang

打算将“文本文件”和程序放在一个集群上,所以我不需要从集群中复制任何文件。我只想登录集群并使用命令:zcat "textfile" | python“myprogram”>“otherfile”,以便 zcat 和程序做他们的事情,我最终在集群上得到“otherfile”。希望你明白我想做什么。

编辑#2:

我的解决方案

#imports
import sys
import fileinput

# Counter, maybe there is a better way
count = 0

# Iterieration over Input
for line in fileinput.input():

    # Selection of Header
    if count == 0 :

        #Format the Header
        newL = '>' + line.replace('@' , '')

        # Print the Header without newline
        sys.stdout.write(newL)

    # Selection of Sequence
    elif count == 1 :

        # Print the Sequence
        sys.stdout.write(line)

    # Up's the Counter
    count += 1
    count = count % 4

谢谢

【问题讨论】:

  • 请说明您的意图。假设您要做的是编写myprogram,则您不需要使用subprocess 模块。在您描述的用例中,myprogram 可以从sys.stdin 读取其输入 - 不需要subprocess。从操作系统执行zcat "textfile" | python "myprogram" 将自动将zcat 的输出定向到myprogram 的STDIN。现在,如果您正在尝试编写 Python 脚本来协调 zcatmyprogram 的执行,那么您可能需要 subprocess
  • 不要将您的工作解决方案放入问题中,而是将其作为答案发布。

标签: bash python-2.7 pipe subprocess


【解决方案1】:

您可以使用fastQ = sys.stdin 从标准输入而不是文件读取输入,或者(更一般地)fastQ = fileinput.input() 从标准输入和/或命令行上指定的文件中读取。

还有fileinput.hook_compressed这样就不需要zcat直接读取压缩文件了:

$ myprogram textfile >otherfile

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多