gpt4 book ai didi

linux - 不关闭 pty 表示不再输入

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:14 24 4
gpt4 key购买 nike

当使用 PTY 主/从对控制进程时,我想向相关进程指示 stdin 已关闭并且我没有更多内容要发送,但我仍想接收进程的输出。

要注意的是,我只有一个文件描述符(PTY“master”),它处理来自子进程的输入和到子进程的输出。所以关闭描述符会关闭两者。

Python 示例:

import subprocess, pty, os
master,slave = pty.openpty()
proc = subprocess.Popen(["/bin/cat"], stdin=slave, stdout=slave)
os.close(slave) # now belongs to child process
os.write(master,"foo")
magic_close_fn(master) # <--- THIS is what I want
while True:
out = os.read(master,4096)
if out:
print out
else:
break
proc.wait()

最佳答案

您需要获取单独的读写文件描述符。做到这一点的简单方法是使用管道和 PTY。所以现在你的代码看起来像这样:

import subprocess, pty, os
master, slave = pty.openpty()
child_stdin, parent_stdin = os.pipe()
proc = subprocess.Popen(["/bin/cat"], stdin=child_stdin, stdout=slave)
os.close(child_stdin) # now belongs to child process
os.close(slave)
os.write(parent_stdin,"foo") #Write to the write end (our end) of the child's stdin
#Here's the "magic" close function
os.close(parent_stdin)
while True:
out = os.read(master,4096)
if out:
print out
else:
break
proc.wait()

关于linux - 不关闭 pty 表示不再输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18225816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com