【问题标题】:How to Use Python Subprocess to Write a String to a File如何使用 Python 子进程将字符串写入文件
【发布时间】:2019-05-17 04:41:18
【问题描述】:

我试图弄清楚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。

【问题讨论】:

  • 为什么不使用open打开一个文件并以正常方式写入?
  • 我正在尝试了解 subprocess 的工作原理
  • 也许从一个更简单的问题开始,比如调用ls 或date 之类的命令并查看它的输出?
  • @DeveshKumarSingh 我试过了。

标签: python subprocess


【解决方案1】:

您的代码无法正常工作,因为您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2015-05-07
    相关资源
    最近更新 更多