【问题标题】:python redirect standard stream of subprocesspython重定向子进程的标准流
【发布时间】:2022-01-02 14:33:55
【问题描述】:

我正在尝试使用 python 作为后端来做在线编码平台。我正在使用subprocess.Popen 运行用户的代码。现在我想和它互动。我知道的一种方法是使用pipedup2 但它的问题是它在我的整个后端应用程序的上下文中改变了标准 i/o。 我希望 std 流仅针对子进程进行更改。

我可以传递给subprocess.Popen 的任何参数,以便主 python 应用程序可以访问其子进程的 std 流?

例子:

import subprocess
args=['py',path+'t.py']
p = subprocess.Popen(args)

t.py 是 Hello World 程序。子进程将在终端打印 Hello World 但我希望它重定向到其他文件描述符,以便我可以访问变量并通过网络发送它。输入也是如此。

更新:

我做到了

r,w=os.pipe()

p = subprocess.Popen(args,stdout=w)

为此我得到错误

 Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'>
OSError: [Errno 22] Invalid argument

【问题讨论】:

  • 您能否展示您的代码以及您尝试了什么?
  • @R.LM 我希望现在清楚我想要做什么。
  • 而你想要的基本上是程序运行正确的输出?
  • @R.LM 也可以控制输入。我期望的是,如果我向某个 fd 写入内容,它应该被输入到该子进程。

标签: python subprocess


【解决方案1】:

subprocess Popen 为这种类型的事物提供了额外的命名参数,正如您所提到的,PIPE

from subprocess import Popen, PIPE, STDOUT

args=['py',path+'t.py']

# errors included
p = Popen(args, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)

#BufferedWriter for input
input_stream = p.stdin

#BufferedReader for output
output_stream = p.stdout


print(output_stream.read())

【讨论】:

    猜你喜欢
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2023-04-05
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多