gpt4 book ai didi

python - subprocess.run() 中的 CompletedProcess 不返回字符串

转载 作者:行者123 更新时间:2023-12-02 10:01:15 25 4
gpt4 key购买 nike

根据Python 3.5 docs , subprocess.run() 返回一个 CompletedProcess 对象,其 stdout 成员包含“一个字节序列,或者一个字符串,如果 run() 是用 universal_newlines=True 调用的。”我只看到一个字节序列而不是一个字符串,我假设(希望)它相当于一个文本行。例如,

import pprint
import subprocess

my_data = ""
line_count = 0

proc = subprocess.run(
args = [ 'cat', 'input.txt' ],
universal_newlines = True,
stdout = subprocess.PIPE)

for text_line in proc.stdout:
my_data += text_line
line_count += 1

word_file = open('output.txt', 'w')
pprint.pprint(my_data, word_file)
pprint.pprint(line_count, word_file)

注意:这使用了 Python 3.5 中的一项新功能,该功能无法在以前的版本中运行。

我是否需要创建自己的行缓冲逻辑,或者有没有办法让 Python 为我做到这一点?

最佳答案

proc.stdout 在您的情况下已经是一个字符串,请运行 print(type(proc.stdout)) 进行确认。它包含所有子进程的输出 - subprocess.run() 在子进程死亡之前不会返回。

for text_line in proc.stdout: 不正确:for char in text_string 枚举 Python 中的字符(Unicode 代码点),而不是行。要获取线路,请调用:

lines = result.stdout.splitlines()

如果字符串中存在 Unicode 换行符,结果可能与 .split('\n') 不同。

如果您想逐行读取输出(以避免长时间运行的进程耗尽内存):

from subprocess import Popen, PIPE

with Popen(command, stdout=PIPE, universal_newlines=True) as process:
for line in process.stdout:
do_something_with(line)

注意:在这种情况下,process.stdout 是一个类似文件的对象。 Popen() 不会等待进程完成 - 一旦子进程启动,Popen() 就会立即返回。 process 是一个 subprocess.Popen 实例,而不是这里的 CompletedProcess

如果您只需要计算输出中的行数(以 b'\n' 终止),例如 wc -l:

from functools import partial

with Popen(command, stdout=PIPE) as process:
read_chunk = partial(process.stdout.read, 1 << 13)
line_count = sum(chunk.count(b'\n') for chunk in iter(read_chunk, b''))

参见Why is reading lines from stdin much slower in C++ than Python?

关于python - subprocess.run() 中的 CompletedProcess 不返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099336/

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