python 从 class 调用时打印 MainThread 而不是 thread-1,-2
python MainThread is printed instead of thread-1,-2 when calling from a class
当我将方法移至 class 时,logging.debug 停止打印线程-#,它现在只打印主线程。我怎样才能让 logging.debug 为每个日志打印 thread-#
代码:
class threadTest():
testResult=''
def __init__(self,nThread,nTests,debugOn):
self.nThread = nThread
self.nTests = nTests
self.debugOn = debugOn
if debugOn == 1:
logging.basicConfig(level=logging.DEBUG,format='[%(levelname)s] (%(threadName)-10s) %(message)s',)
@classmethod
def test(cls):
if debugOn == 1: logging.debug('Starting')
...do something...
if debugOn == 1: logging.debug('Exiting')
time.sleep(1)
arguments=sys.argv
nThread = int(sys.argv[1]) if len(sys.argv)>1 else 1
nTests = int(sys.argv[2]) if len(sys.argv)>2 else 1
debugOn = int(sys.argv[3]) if len(sys.argv)>3 else 0
myThread = threadTest(nThread,nTests,debugOn)
x=1
while x <= nThread:
thread='Thread-'+str(x)
t=threading.Thread(name=thread, target=myThread.test())
t.start()
x+=1
time.sleep(1)
当前输出:
[DEBUG] (MainThread) Starting
[INFO] (MainThread) Starting new ...
[DEBUG] (MainThread) Exiting
[DEBUG] (MainThread) Starting
[INFO] (MainThread) Starting new ...
[DEBUG] (MainThread) Exiting
预期输出:
[DEBUG] (Thread-1) Starting
[INFO] (Thread-1) Starting new ...
[DEBUG] (Thread-1) Exiting
[DEBUG] (Thread-2) Starting
[INFO] (Thread-2) Starting new ...
[DEBUG] (Thread-2) Exiting
感谢@tdelaney 指出问题所在。
t=threading.Thread(name=thread, target=myThread.test())
已更改为
t=threading.Thread(name=thread, target=myThread.test)
Thread-1,-2.... 现在出现
当我将方法移至 class 时,logging.debug 停止打印线程-#,它现在只打印主线程。我怎样才能让 logging.debug 为每个日志打印 thread-#
代码:
class threadTest():
testResult=''
def __init__(self,nThread,nTests,debugOn):
self.nThread = nThread
self.nTests = nTests
self.debugOn = debugOn
if debugOn == 1:
logging.basicConfig(level=logging.DEBUG,format='[%(levelname)s] (%(threadName)-10s) %(message)s',)
@classmethod
def test(cls):
if debugOn == 1: logging.debug('Starting')
...do something...
if debugOn == 1: logging.debug('Exiting')
time.sleep(1)
arguments=sys.argv
nThread = int(sys.argv[1]) if len(sys.argv)>1 else 1
nTests = int(sys.argv[2]) if len(sys.argv)>2 else 1
debugOn = int(sys.argv[3]) if len(sys.argv)>3 else 0
myThread = threadTest(nThread,nTests,debugOn)
x=1
while x <= nThread:
thread='Thread-'+str(x)
t=threading.Thread(name=thread, target=myThread.test())
t.start()
x+=1
time.sleep(1)
当前输出:
[DEBUG] (MainThread) Starting
[INFO] (MainThread) Starting new ...
[DEBUG] (MainThread) Exiting
[DEBUG] (MainThread) Starting
[INFO] (MainThread) Starting new ...
[DEBUG] (MainThread) Exiting
预期输出:
[DEBUG] (Thread-1) Starting
[INFO] (Thread-1) Starting new ...
[DEBUG] (Thread-1) Exiting
[DEBUG] (Thread-2) Starting
[INFO] (Thread-2) Starting new ...
[DEBUG] (Thread-2) Exiting
感谢@tdelaney 指出问题所在。
t=threading.Thread(name=thread, target=myThread.test())
已更改为
t=threading.Thread(name=thread, target=myThread.test)
Thread-1,-2.... 现在出现