簡體   English   中英

如何在Python中同時使用COM和多重處理?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM