从类调用时,打印python MainThread而不是thread1,2

2024-09-30 18:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

当我把我的方法移植到一个类中时,日志记录.debug停止打印线程-#,它现在只打印主线程。我怎么才能得到日志记录.debug为每个日志打印线程

代码:

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)

电流输出:

^{pr2}$

预期产量:

[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

Tags: debugselflenifloggingsysthreadint