2016-08-16 67 views
0

我試圖在python中複製C#代碼,它執行一個線程,等待它完成並返回一個值。實質上,方法RunAndWait位於助手類中,因爲對該方法的調用正在進行多次。從另一個模塊的不同線程接收返回值

C#代碼如下:

public static bool RunAndWait(Action _action, long _timeout) 
    { 
     Task t = Task.Run(() => 
     { 
      Log.Message(Severity.MESSAGE, "Executing " + _action.Method.Name); 
      _action(); 
     }); 
     if (!t.Wait(Convert.ToInt32(_timeout))) 
     { 
      Log.Message(Severity.ERROR, "Executing " + _action.Method.Name + " timedout. Could not execute MCS command."); 
      throw new AssertFailedException(); 
     } 
     t.Dispose(); 
     t = null; 
     return true; 
    } 

python我一直在掙扎了幾件事情。首先,似乎有不同類型的Queue,我只是簡單地選擇了似乎正在工作的導入import Queue。其次,我收到TypeError如下。

Traceback (most recent call last): File "C:/Users/JSC/Documents/Git/EnterprisePlatform/Enterprise/AI.App.Tool.AutomatedMachineTest/Scripts/monkey.py", line 9, in File "C:\Users\JSC\Documents\Git\EnterprisePlatform\Enterprise\AI.App.Tool.AutomatedMachineTest\Scripts\Libs\MonkeyHelper.py", line 4, in RunCmdAndWait TypeError: module is not callable

這裏是猴子python代碼:

from Libs.CreateConnection import CreateMcsConnection 
import Libs.MonkeyHelper as mh 
import Queue 

q = Queue.Queue() 
to = 5000 #timeout 

mh.RunCmdAndWait(CreateMcsConnection, to, q) 
serv, con = q.get() 

MonkeyHelper.py

import threading 

def RunCmdAndWait(CmdToRun, timeout, q): 
    t = threading(group=None, target=CmdToRun, arg=q) 
    t.start() 
    t.join(timeout=timeout) 

我不知道我做錯了。我對python相當陌生。有人可以幫我嗎?

編輯

t = threading.Thread(group=None, target=CmdToRun, args=q) 

解決以上行帶來了一個錯誤:

Exception in thread Thread-1: Traceback (most recent call last): File "C:\Program Files (x86)\IronPython 2.7\Lib\threading.py", line 552, in _Thread__bootstrap_inner self.run() File "C:\Program Files (x86)\IronPython 2.7\Lib\threading.py", line 505, in run self.target(*self.__args, **self.__kwargs) AttributeError: Queue instance has no attribute '__len'

是不是因爲Thread預計多ARGS或者因爲queue仍然是空的,在這一點?從我看到的是,queue只是作爲參數傳遞來接收返回值。這是正確的路嗎?

EDIT2

在下面一個TypeError改變t = threading.Thread(group=None, target=CmdToRun, args=q)t = threading.Thread(group=None, target=CmdToRun, args=(q,))

的變化率,似乎怪我,因爲線程期待一個元組。

Exception in thread Thread-1: Traceback (most recent call last): File "C:\Program Files (x86)\IronPython 2.7\Lib\threading.py", line 552, in _Thread__bootstrap_inner self.run() File "C:\Program Files (x86)\IronPython 2.7\Lib\threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) TypeError: tuple is not callable

+0

你想'threading.Thread()'。如果你仔細看看錯誤,這將是有道理的。 – sberry

回答

1

threading是一個模塊。您可能意味着與

t = threading.Thread(group=None, target=CmdToRun, args=(q,)) 

args一種說法元組來替換

t = threading(group=None, target=CmdToRun, arg=q) 

+0

謝謝,這解決了這個問題。我看到模塊是線程,而對象是線程。這引發了一個新的錯誤。請參閱編輯。 –

+0

再次感謝您的幫助。我調整了傳遞'args =(q,)'的第二個改變,這導致了'TypeError:元組不可調用'。 –