【问题标题】:python MainThread is printed instead of thread-1,-2 when calling from a class从类调用时打印 python MainThread 而不是 thread-1,-2
【发布时间】:2016-03-31 02:53:02
【问题描述】:

当我将我的方法移动到一个类中时,logging.debug 停止打印线程-#,它现在只打印主线程。如何让 logging.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)

当前输出:

[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

【问题讨论】:

  • t=threading.Thread(name=thread, target=myThread.test()) - 你在启动线程之前调用测试。
  • 你建议我如何解决它?
  • 好吧,我通过删除 t=threading.Thread(name=thread, target=myThread.test()) 中的 () 来打印要打印的线程,使其看起来像:t=threading。线程(名称=线程,目标=myThread.test)
  • 对不起,我回来晚了……但是,是的,这就是你想要做的。你给函数对象(myThread.test),让线程调用函数。

标签: python multithreading multiprocessing threadpool python-multithreading


【解决方案1】:

感谢@tdelaney 指出问题所在。

t=threading.Thread(name=thread, target=myThread.test())

改为

t=threading.Thread(name=thread, target=myThread.test)

Thread-1,-2.... 现在出现

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2012-01-10
    • 2019-07-20
    • 2017-08-29
    相关资源
    最近更新 更多