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

时间:2019-05-17 04:41:19

标签: python subprocess

我试图弄清楚subprocess中会发生什么。 所以,我编写这段代码:

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中。

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为您的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