【问题标题】:print current thread in python 3在python 3中打印当前线程
【发布时间】:2017-01-10 05:28:39
【问题描述】:

我有这个脚本:

import threading, socket

for x in range(800)
    send().start()

class send(threading.Thread):
    def run(self):
        while True:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect(("www.google.it", 80))
                s.send ("test")
                print ("Request sent!")
            except:
                pass

在“请求已发送!”的地方我想打印类似:"Request sent! %s" % (当前发送请求的线程数)

最快的方法是什么?

--已解决--

import threading, socket

for x in range(800)
    send(x+1).start()

class send(threading.Thread):
    def __init__(self, counter):
        threading.Thread.__init__(self)
        self.counter = counter
    def run(self):
        while True:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect(("www.google.it", 80))
                s.send ("test")
                print ("Request sent! @", self.counter)
            except:
                pass

【问题讨论】:

标签: python multithreading sockets python-3.x


【解决方案1】:

您可以将计数号(在本例中为x)作为发送类中的变量传递。请记住,x 将从 0 开始,而不是 1。

for x in range(800)
    send(x+1).start()

class send(threading.Thread):
    def __init__(self, count):
        self.count = count

    def run(self):
        while True:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect(("www.google.it", 80))
                s.send ("test")
                print ("Request sent!"), self.count
            except:
                pass

或者,正如 Rob 在上面另一个问题中所评论的那样,threading.current_thread() 看起来令人满意。

【讨论】:

  • 感谢您的回答。它引发:[code] raise RuntimeError("thread.__init__() not called") RuntimeError: thread.__init__() not called [/code]
  • 通过将“threading.Thread.__init__(self)”添加到init函数来解决。谢谢
  • 但我还是不明白为什么 send(x+1).start() 有这个 +1
  • @allexj 这是因为range(800)以0而不是1开头,所以当我们说“请求已发送!”我们第一次说“这是第一个!”而不是“这是第零个!”
【解决方案2】:

最简单的方法是使用setNamegetName 为您的线程命名。

import threading, socket

for x in range(800)
    new_thread = send()
    new_thread.setName("thread number %d" % x)
    new_thread.start()

class send(threading.Thread):
    def run(self):
        while True:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect(("www.google.it", 80))
                s.send ("test")
                print ("Request sent by %s!" % self.getName())
            except:
                pass

您还可以向send 添加您需要跟踪您的线程的任何其他属性。

【讨论】:

    【解决方案3】:

    只是关于如何获取当前线程的线程ID的一个侧面答案(可能不会直接回答问题,但可以帮助其他人): 在 python 3.3+ 中你可以简单地做:

    import threading
    
    threading.get_ident()
    

    阅读更多:here

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      相关资源
      最近更新 更多