Python 3.3多线程参数序列

时间:2013-06-12 14:05:25

标签: python multithreading arguments sequence

在FOR循环运行时,我一直在编写一小段代码来测试线程,并在不同的类中运行不同的函数。

代码运行良好,但如果你想要它超过10秒的线程,IDLE会出现以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python33\lib\threading.py", line 637, in _bootstrap_inner
self.run()
File "C:\Python33\lib\threading.py", line 594, in run
self._target(*self._args, **self._kwargs)
TypeError: main() takes 2 positional arguments but 3 were given

这似乎是threading.py模块的一个问题,但肯定有一个解决方案。

下面是我的代码:

import threading, time

class Application:
    def __init__(self):       
        self.main()

    def main(self)        
        global count
        count = int(input("How many seconds do you want it to Thread?\n"))
        if count:
            thread = Threading(count)
        else:
            pass

    def test(self):
        print("Printing in another class.", self)


class Threading:
    def __init__(self, y):
        print("Starting Thread...")
        number = str(count)
        thread = threading.Thread(target=self.main, args=number)
        thread.start()
        for i in range(count):          
            print("Looping...", i)
            time.sleep(1)

    def main(self, argument):
        while (int(argument)>0):
            print("Threading...", argument)
            argument = int(argument) - 1
            Application.test(argument)
            time.sleep(1)

if __name__ == '__main__':
    app = Application()

如果我更改了代码中的strint部分,则线程根本不会运行,因为文件必须是序列。 所以我的问题是,如何使代码能够运行超过10秒“。

1 个答案:

答案 0 :(得分:1)

自己想出来! 参数必须是一个元组,所以我将原始的多线程更改为以下内容:

 thread = threading.Thread(target=self.main, args=(number,))

之前只有args=number