Python 字符串作为具有多处理访问的发送缓冲区
在Python中,如何用数据行(字符串)填充缓冲区,并用第二个进程使用它?这里有大量的示例,可以从字符串中添加和读取行,但是我需要从字符串中删除已使用的行,以便该字符串可以用作缓冲区 示例:从串行端口读取零星数据,并通过TCP/IP将其发送到服务器。一个循环内逐行且无缓冲=没有问题,但如果无法到达目的地,则应将数据存储在缓冲区中,然后在连接可用时发送Python 字符串作为具有多处理访问的发送缓冲区,python,sockets,serial-port,multiprocessing,Python,Sockets,Serial Port,Multiprocessing,在Python中,如何用数据行(字符串)填充缓冲区,并用第二个进程使用它?这里有大量的示例,可以从字符串中添加和读取行,但是我需要从字符串中删除已使用的行,以便该字符串可以用作缓冲区 示例:从串行端口读取零星数据,并通过TCP/IP将其发送到服务器。一个循环内逐行且无缓冲=没有问题,但如果无法到达目的地,则应将数据存储在缓冲区中,然后在连接可用时发送 #!/usr/bin/python import serial import socket from multiprocessing import
#!/usr/bin/python
import serial
import socket
from multiprocessing import Process
ip = "someURL"
port = 12345
ser = serial.Serial("/dev/ttyUSB0", 57600, timeout=0)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def serial_reader():
while True:
for line in ser.read():
try:
response = ser.readlines(None)
response = str(response)
message = response[7:]
except:
print datetime.datetime.now(), " No data from serial connection."
##
def data_sender():
s.connect((ip, port))
while True:
for line in queue():
try:
s.send(message)
except:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
continue
except:
s.close()
##
if __name__ == '__main__':
Process(target=serial_reader).start()
Process(target=data_sender).start()
我认为实现目标的最佳方法是使用队列: 来自多处理导入队列的
具体使用queue.put()
在队列上放置字符串,使用queue.get()
检索它,使用queue.task\u done()
指示任务已完成
如果您需要更大的枪,请查看实现AMPQ协议的RabbitMQ和python库,例如rabbitpy
。这是进程间/服务间通信的实际标准,并且已经加入了许多有用的东西,例如在进程关闭时持久化消息、跨多个进程的负载平衡任务等