'", myfile-6ren">
gpt4 book ai didi

Python subprocess communicate() yields None,当需要数字列表时

转载 作者:太空狗 更新时间:2023-10-30 00:35:25 26 4
gpt4 key购买 nike

当我运行下面的代码时

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

我的文件看起来像这样:

>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]

返回类型为 None 的某种对象(而不是整数列表)?

我知道我可以在简单的情况下使用 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])

关于Python subprocess communicate() yields None,当需要数字列表时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34458373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com