我試圖在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
你想'threading.Thread()'。如果你仔細看看錯誤,這將是有道理的。 – sberry