[英]Accessing the state of a Python Multiprocessing.Process subclass from the parent process
我正在创建一个简单的TCP服务器作为存根,因此我可以测试运行一个测试设备的脚本,而不必在那里安装设备。 服务器应坐在那里等待连接,然后根据收到的命令维护和更新状态变量(仅由6个整数组成的列表)。 然后,父进程(例如,单元测试类)应该能够查询状态。
服务器的接口应尽可能简单:
server = StubServer()
server.start()
'''
the client script connects with the server and
some stuff happens to change the state
'''
newState = server.getState() # newState = [93,93,93,3,3,45] for example
server.terminate()
我将Multiprocessing.Process子类化,可以做到这一点,并且我可以毫无问题地启动服务器。 第一次测试时,在getState()方法中,我只是返回了实例变量_state,但我发现这始终只是初始状态。 经过一番挖掘,我找不到任何类似的例子。 关于子类化处理的很多东西,但不是这个特定的问题。 最终,我将下面的代码放在一起,它使用内部Queue()来存储状态,但是对我来说这看起来很凌乱和笨拙。 有一个更好的方法吗?
import socket
from multiprocessing import Process, Queue
class StubServer(Process):
_port = 4001
_addr = '' # all addresses 0.0.0.0
_sock = None
_state = []
_queue = None
def __init__(self, initState=[93,93,93,93,93,93]):
super(StubServer, self).__init__()
self._queue = Queue()
self._state = initState
def run(self):
# Put the state into the queue
self._queue.put(self._state)
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.bind((self._addr, self._port))
self._sock.listen(1)
waitingForConnection = True
'''
Main loop will continue until the connection is terminated. if a connection is closed, the loop returns
to the start and waits for a new connection. This means multiple tests can be run with the same server
'''
while 1:
# Wait for a connection, or go back and wait for a new message (if a connection already exists)
if waitingForConnection:
waitingForConnection = False
conn, addr = self._sock.accept()
chunk = ''
chunks = []
while '\x03' not in chunk: # '\x03' is terminating character for a message
chunk = conn.recv(8192)
if not chunk: # Connection terminated, start the loop again and wait for a new connection
waitingForConnection = True
break
chunks.append(chunk)
message = ''.join(chunks)
# Now do some stuff to parse the message, and update the state if we received a command
if isACommand(message):
_updateState(message)
conn.close()
return
def getState(self):
# This is called from the parent process, so return the object on the queue
state = self._queue.get()
# But put the state back in the queue again so it's there if this method is called again before a state update
self._queue.put(state)
return state
def _updateState(self, message):
# Do some stuff to figure out what to update then update the state
self._state[updatedElementIndex] = updatedValue
# Now empty the queue and put the new state in the queue
while not self._queue.empty():
self._queue.get()
self._queue.put(self._state)
return
您可以随时将存根服务器的状态转储到文件中,并从单元测试中读取它。 这是满足测试需求的非常简单的解决方案。
您需要做的所有事情:
filename
作为参数传递给构造函数 _updateState
_updateState
以将状态写入filename
。 最好在文件filename
附近创建一个新文件并替换它。 如果您担心原子性。 谢谢费利佩,我的问题主要是“像使用问题一样,有没有比使用队列更好的方法”。 经过更多研究(提示您提到共享内存)后,我发现对于这种情况,共享阵列要好得多:
import socket
from multiprocessing import Process, Array
class StubServer(Process):
_port = 4001
_addr = '' # all addresses 0.0.0.0
_sock = None
_state = None
_queue = None
def __init__(self, initState=[93,93,93,93,93,93]):
super(StubServer, self).__init__()
self._state = Array('i', initState) # Is always a 6 element array
def run(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.bind((self._addr, self._port))
self._sock.listen(1)
waitingForConnection = True
'''
Main loop will continue until process is terminated. if a connection is closed, the loop returns
to the start and waits for a new connection. This means multiple tests can be run with the same server
'''
while 1:
# Wait for a connection, or go back and wait for a new message (if a connection already exists)
if waitingForConnection:
waitingForConnection = False
conn, addr = self._sock.accept()
chunk = ''
chunks = []
while '\x03' not in chunk: # '\x03' is terminating character for a message
chunk = conn.recv(8192)
if not chunk: # Connection terminated, start the loop again and wait for a new connection
waitingForConnection = True
break
chunks.append(chunk)
message = ''.join(chunks)
# Now do some stuff to parse the message, and update the state if we received a command
if isACommand(message):
_updateState(message)
conn.close()
return
def getState(self):
# Aquire the lock return the contents of the shared array
with self._state.get_lock():
return self._state[:6] # This is OK because we know it is always a 6 element array
return state
def _updateState(self, message):
# Do some stuff to figure out what to update then..
# Aquire the lock and update the appropriate element in the shared array
with self._state.get_lock():
self._state[updatedElementIndex] = updatedValue
return
这可以使人愉悦,并且更加优雅。 谢谢你的帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.