繁体   English   中英

Python线程参数问题

[英]Python Threading Parameters Issue

我已经尝试了大约半小时,但似乎无法将我的错误全神贯注。 工作代码:

import threading
from time import sleep


def printX():
    threading.Timer(5.0, printX).start()
    print("five")


printX()
while True:
    print("1")
    sleep(1)

这可行,但是我需要能够动态分配打印语句以及延迟。 所需代码:

import threading
from time import sleep


def printX(time, message):
    threading.Timer(int(time), printX).start()
    print(str(message)


printX(time, message)
while True:
    print("Rest of the program continues")
    sleep(1)

感谢您的任何提前帮助:)。

threading.Timer可以使用args传递参数:

threading.Timer(int(time), printX, (time, message)).start()

阅读其文档的更多信息。

另一种方法是使用printX作为内部函数定义一个类。

class thread:

    def __init__(self, time, message):
        self.time = time
        self.message = message

    def printX(self):
        threading.Timer(int(self.time), self.printX).start()
        print(str(self.message))

thread(3,"test message").printX()

while True:
    print("Rest of the program continues")
    sleep(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM