我想做的是,在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之后)?在
不幸的是,在该过程的持续时间内,除了从自己的stdin读取并写入该进程之外,没有标准方法将自己的stdin拼接到其他进程的stdin,只要您选择首先写入该进程。
也就是说,您可以这样做:
该过程将继承您的stdin;或者您可以执行以下操作:
^{pr2}$然后你提供了stdin到这个过程。但是一旦你选择提供了stdin的任何的供应,你就可以提供stdin的所有了,即使这意味着你必须阅读自己的stdin。
Linux提供^{cd1>}系统调用(documentation at man7.org、documentation at linux.die.net、Wikipedia、linux pipe data from file descriptor into a fifo),但您最好的选择可能是一个后台线程来复制数据。
相关问题 更多 >
编程相关推荐