[英]How can I use COM and multiprocessing at the same time in Python?
我正在尝试进行两个过程并使它们彼此通信。 其中一个通过使用Win32com的COM库获取值,另一个通过队列从第一个进程获取值并打印出来。 我认为下面的代码没有问题,但是不起作用(p2进程根本不显示值)。 如果我只是使第一个进程在同一进程中打印队列值,则
item = self.q.get()
print(item)
它显示队列中的值。 因此,我认为将值放入队列中没有问题,因此,使用win32com
通过queue
交换值时可能会出现一些问题。
import win32com.client
import os
import multiprocessing as mp
from PyQt4.QtGui import QApplication
from datetime import datetime, timedelta
global q
q = mp.Queue() # A queue is used to send values from p1 to p2
class RealTrEventHandler(object):
def __init__(self):
self.q = q
def OnReceiveRealData(self,szTrCode):
date = datetime.utcnow() + timedelta(hours=3)
type = self.GetFieldData("OutBlock", "cgubun")
appending_line = date + ', ' + type
self.q.put(appending_line)
#item = self.q.get() # it prints values out if these are not comments
#print(item)
def ticker():
loop = QApplication([])
global instXASession, instXAReal
print('TICKER: ', os.getpid() )
# When an event occurs, it calls RealTrEventHandler class
instXAReal = win32com.client.DispatchWithEvents("XA_DataSet.XAReal", RealTrEventHandler)
instXAReal.LoadFromResFile("C:\\eBEST\\xingAPI\\Res\\OVC.res")
instXAReal.SetFieldData("InBlock", "symbol", "CLX17")
loop.exec_()
class listener(mp.Process): # What listener does is only to get values via the queue and prints them out
def __init__(self):
mp.Process.__init__(self)
self.q = q
def run(self):
print('CSM PID: ', os.getpid() )
while True:
item = self.q.get()
print(item)
if __name__ == '__main__':
loop = QApplication([])
print('MAIN: ', os.getpid() )
p1 = mp.Process( target = ticker, args=() )
p1.start()
p2 = listener()
p2.start()
mp.freeze_support()
loop.exec_()
有人可以给我一些建议吗?
您是否尝试在侦听器和RealTrEventHandler类中将q明确声明为全局变量? 例如:
class listener(mp.Process):
global q
def __init__(self):
mp.Process.__init__(self)
self.q=q
在(至少)线程之间传递变量的另一种方法是使用buildins-module,但是我不确定多处理是否有很大不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.