如何解决python中使用CreatePseudoConsole创建pty管道的问题
我正在尝试制作一个 pty 管道。为此,我必须使用 Windows api 中的 CreatePseudoConsole
函数。我正在松散地复制 this,它是 this 但在 python 中。
我不知道它是否相关,但我使用的是 Python 3.7.9 和 Windows 10。
这是我的代码:
from ctypes.wintypes import DWORD,HANDLE,SHORT
from ctypes import POINTER,POINTER,HRESULT
import ctypes
import msvcrt
import os
# The COORD data type used for the size of the console
class COORD(ctypes.Structure):
_fields_ = [("X",SHORT),("Y",SHORT)]
# HPCON is the same as HANDLE
HPCON = HANDLE
CreatePseudoConsole = ctypes.windll.kernel32.CreatePseudoConsole
CreatePseudoConsole.argtypes = [COORD,DWORD,POINTER(HPCON)]
CreatePseudoConsole.restype = HRESULT
def create_console(width:int,height:int) -> HPCON:
read_pty_fd,write_fd = os.pipe()
read_pty_handle = msvcrt.get_osfhandle(read_pty_fd)
read_fd,write_pty_fd = os.pipe()
write_pty_handle = msvcrt.get_osfhandle(write_pty_fd)
# Create the console
size = COORD(width,height)
console = HPCON()
result = CreatePseudoConsole(size,read_pty_handle,write_pty_handle,DWORD(0),ctypes.byref(console))
# Check if any errors occured
if result != 0:
raise ctypes.WinError(result)
# Add references for the fds to the console
console.read_fd = read_fd
console.write_fd = write_fd
# Return the console object
return console
if __name__ == "__main__":
consol = create_console(80,80)
print("Writing...")
os.write(consol.write_fd,b"abc")
print("Reading...")
print(os.read(consol.read_fd,1))
print("Done")
问题是它无法从管道中读取。我预计它会打印 "a"
,但它只是卡在 os.read
上。请注意,这是我第一次使用 WinAPI,所以问题很可能存在。
解决方法
代码没有错:你错的是你的期望。
您正在做的是写入管道,以将“键盘”输入提供给程序,并从另一个管道中读取,该管道从程序返回“屏幕”输出。但是在任一管道的另一端都没有实际程序,因此 read 调用无法返回任何内容。
HPCON
API 返回的 CreatePseudoConsole
句柄应该在线程属性列表中通过 CreateProcess
传递给新生成的进程。除此之外,几乎没有什么可以用它做的。 (您甚至无法将自己连接到伪控制台,就像在 Unix 上一样。)以这种方式传递句柄后,您可以使用 read_fd
和 write_fd
描述符与进程通信。
article on MSDN 提供了一个完整的 C 语言示例,它创建了一个伪控制台并将其传递给一个新进程; exact same thing 由您链接的源完成。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。