【发布时间】:2016-10-16 16:46:46
【问题描述】:
我有一个 (非常) 用 C 编写的简单 Web 服务器,我想对其进行测试。我写了它,所以它在标准输入上获取数据并在标准输出上发送出去。如何将套接字(使用 socket.accept() 创建)的输入/输出连接到使用 subprocess.Popen 创建的进程的输入/输出?
听起来很简单,对吧?这是杀手锏:我正在运行 Windows。
谁能帮忙?
这是我尝试过的:
- 将客户端对象本身作为标准输入/输出传递给 subprocess.Popen。 (尝试永远不会有坏处。)
- 将 socket.makefile() 结果作为标准输入/输出传递给 subprocess.Popen。
- 将套接字的文件号传递给 os.fdopen()。
另外,如果问题不清楚,这里是我的代码的精简版:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()
p = subprocess.Popen([PROG])
#I want to connect 'p' to the 'cli' socket so whatever it sends on stdout
#goes to the client and whatever the client sends goes to its stdin.
#I've tried:
p = subprocess.Popen([PROG], stdin = cli.makefile("r"), stdout = cli.makefile("w"))
p = subprocess.Popen([PROG], stdin = cli, stdout = cli)
p = subprocess.Popen([PROG], stdin = os.fdopen(cli.fileno(), "r"), stdout = os.fdopen(cli.fileno(), "w"))
#but all of them give me either "Bad file descriptor" or "The handle is invalid".
【问题讨论】:
-
我遇到了同样的问题,但我想出的解决方案是共享套接字,将套接字端口写入进程的标准输入或使用
socket.share函数(在 python 中) .我认为你至少应该考虑这个解决方案。
标签: python windows sockets process