当我运行以下代码
from subprocess import call, check_output, Popen, PIPE
gr = Popen(["grep", "'^>'", myfile], stdout=PIPE)
sd = Popen(["sed", "s/.*len=//"], stdin=gr.stdout)
gr.stdout.close()
out = sd.communicate()[0]
print out
myfile如下所示:
>name len=345
sometexthere
>name2 len=4523
someothertexthere
...
...
我懂了
None
当期望的输出是数字列表时:
345
4523
...
...
我在终端中运行的相应命令是
grep "^>" myfile | sed "s/.*len=//" > outfile
到目前为止,我已经尝试过以不同的方式进行转义和引用,例如在sed中转义斜线或为grep添加额外的引号,但是组合的可能性很大。
我还考虑过仅读取文件并编写grep和sed的Python等效文件,但是文件很大(尽管我总是可以逐行读取),它将始终在基于UNIX的系统上运行,我仍然对此感到好奇我犯了错误。
可能是
sd.communicate()[0]
返回某种类型的对象(而不是整数列表)?
我知道我可以在简单的情况下使用check_output来获取输出:
sam = check_output(["samn", "stats", myfile])
但不确定如何处理越来越复杂的情况。
有什么生产方法可以通过子流程获得预期结果?
如建议的那样,您需要stdout=PIPE
在第二个过程中删除以下内容中的单引号"'^>'"
:
gr = Popen(["grep", "^>", myfile], stdout=PIPE)
Popen(["sed", "s/.*len=//"], stdin=gr.stdout, stdout=PIPE)
......
但这可以简单地使用纯python和来完成re
:
import re
r = re.compile("^\>.*len=(.*)$")
with open("test.txt") as f:
for line in f:
m = r.search(line)
if m:
print(m.group(1))
哪个会输出:
345
4523
如果以开头开头的行>
始终带有数字,而之后的数字始终位于结尾,len=
那么您实际上也不需要正则表达式:
with open("test.txt") as f:
for line in f:
if line.startswith(">"):
print(line.rsplit("len=", 1)[1])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句