【发布时间】: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 脚本来协调zcat和myprogram的执行,那么您可能需要subprocess。 -
不要将您的工作解决方案放入问题中,而是将其作为答案发布。
标签: bash python-2.7 pipe subprocess