你的目的是什么`tempfile.NamedTemporaryFile文件`在使用zmq创建客户端时?

2024-10-04 01:33:46 发布

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

我正在阅读AMP的源代码,当代码使用zmq创建客户机时,我对tempfile.NamedTemporaryFile的目的感到困惑。你知道吗

下面是代码工作原理的示意图:

服务器:

import pexpect
import sys
import zmq
from socket import gethostname

python = sys.executable
context = zmq.Context()
socket = context.socket(zmq.REP)
port = socket.bind_to_random_port('tcp://*')
serverhostname = gethostname()
serversocket = '%s:%s' % (serverhostname, port)
workercommand = "%s -m %s %s" % (python, <python_module>, serversocket)

child = pexpect.spawn(workercommand)
child.expect('<amp-connect>')

通过运行<python-module>,将创建一个客户机

客户:

import zmq
import sys
import tempfile

print('<amp-connect>')
sys.stderr = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.stderr')
sys.stderr.write('initiated\n')
sys.stderr.flush()
context = zmq.Context()

sys.stderr.write('context started\n')
sys.stderr.flush()
socket = context.socket(zmq.REQ)

sys.stderr.write('socket started\n')
sys.stderr.flush()
socket.connect('tcp://%s' % hostsocket)

我的困惑:

  1. sys.stderr = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.stderr')的目的是什么?为什么客户机必须与这些sys.stderr行一起创建?

  2. 为什么child.expect('<amp-connect>')在代码中工作?

我写了一个类似的代码。你知道吗

import pexpect
import sys
import test
python = sys.executable
workercommand = "%s -m %s" % (python, test)
child = pexpect.spawn(workercommand)
child.expect('<ahh>')
print(child.before)

其中test.py只是

print(100)
print('<ahh>')

但是,我得到了一个错误: pexpect.exceptions.EOF: End Of File (EOF). Empty string style platform.

为什么我的代码不起作用?你知道吗


Tags: 代码importchild客户机connectstderrsyscontext