如何在使用管道后将子进程控制传递给常规stdin?

2024-05-29 03:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是,在Python中,通过stdin以编程方式将一些初始命令发送给进程,然后将输入传递给用户,让他们随后控制程序。Python程序只需等待子进程因用户输入而退出。从本质上讲,我想做的是:

import subprocess

p = subprocess.Popen(['cat'], stdin=subprocess.PIPE)

# Send initial commands.
p.stdin.write(b"three\ninitial\ncommands\n")
p.stdin.flush()

# Give over control to the user.
# …Although stdin can't simply be reassigned
# in post like this, it seems.
p.stdin = sys.stdin

# Wait for the subprocess to finish.
p.wait()

如何将stdin传递回用户(不使用raw_input,因为我需要用户的输入在每次按键时生效,而不仅仅是在按enter之后)?在


Tags: theto用户import命令程序进程编程
1条回答
网友
1楼 · 发布于 2024-05-29 03:21:06

不幸的是,在该过程的持续时间内,除了从自己的stdin读取并写入该进程之外,没有标准方法将自己的stdin拼接到其他进程的stdin,只要您选择首先写入该进程。

也就是说,您可以这样做:

proc = subprocess.Popen(...)  # no stdin=

该过程将继承您的stdin;或者您可以执行以下操作:

^{pr2}$

然后你提供了stdin到这个过程。但是一旦你选择提供了stdin的任何的供应,你就可以提供stdin的所有了,即使这意味着你必须阅读自己的stdin。

Linux提供^{cd1>}系统调用(documentation at man7.orgdocumentation at linux.die.netWikipedialinux pipe data from file descriptor into a fifo),但您最好的选择可能是一个后台线程来复制数据。

相关问题 更多 >

    热门问题