gpt4 book ai didi

python - 如何使用 Python 子进程将字符串写入文件

转载 作者:行者123 更新时间:2023-12-01 00:56:47 25 4
gpt4 key购买 nike

我试图弄清楚子进程中发生了什么。所以,我写了这段代码:

import subprocess

p1 = subprocess.Popen('grep a', stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell=True, universal_newlines=True)
p2 = subprocess.Popen('grep a', stdin=p1.stdout, stdout=open('test', 'w'),shell=True, universal_newlines=True)

p1.stdin.write("asdads"*700)

将字符串写入 p1.stdin 后,我希望将字符串写入文件 test。但文件中什么也没有。

当我尝试另一种方式时:

out, err = p1.communicate("adsad"*700)

字符串位于out中。

最佳答案

您的代码无法正常工作,因为您的 stdin 流未关闭。为了证明我所说的:

p1 = subprocess.Popen('grep l', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
out, err = p1.communicate('hello')

>>> out
'hello\n'

现在使用communicate进行测试,它会自动为您关闭流。

p1 = subprocess.Popen('grep l', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
p2 = subprocess.Popen('grep h', stdin=p1.stdout, stdout=open('test', 'w'),shell=True, universal_newlines=True)

# test is already created and empty
# but call communicate again can write to file
>>> p1.communicate('hello')
('', None)

$cat test
hello

另一种方式:

# use stdin.write
>>> p1.stdin.write('hello') # empty file
>>> p1.stdin.close() # flushed

引用文献:

  1. subprocess popen.communicate() vs. stdin.write() and stdout.read()
  2. https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

关于python - 如何使用 Python 子进程将字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56179723/

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