Skip to main content
 首页 » 编程设计

python之学习 Python 线程模块

2025年05月04日14qlqwjy

我正在尝试了解有关线程模块的更多信息。我想出了一个快速脚本,但在运行它时出现错误。文档显示格式为:

thread.start_new_thread ( function, args[, kwargs] ) 

我的方法只有一个参数。

#!/usr/bin/python 
 
import ftplib 
import thread 
 
sites = ["ftp.openbsd.org","ftp.ucsb.edu","ubuntu.osuosl.org"] 
 
def ftpconnect(target): 
        ftp = ftplib.FTP(target) 
        ftp.login() 
        print "File list from: %s" % target 
        files = ftp.dir() 
        print files 
 
for i in sites: 
    thread.start_new_thread(ftpconnect(i)) 

我看到的错误发生在 for 循环的一次迭代之后:

Traceback (most recent call last): File "./ftpthread.py", line 16, in thread.start_new_thread(ftpconnect(i)) TypeError: start_new_thread expected at least 2 arguments, got 1

如果您对此学习过程有任何建议,我们将不胜感激。我也研究过使用线程,但我无法导入线程,因为它显然没有安装,而且我还没有找到任何安装该模块的文档。

谢谢!

尝试在我的 Mac 上导入线程时出现的错误是:

>>> import threading 
# threading.pyc matches threading.py 
import threading # precompiled from threading.pyc 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "threading.py", line 7, in <module> 
    class WorkerThread(threading.Thread) : 
AttributeError: 'module' object has no attribute 'Thread' 

请您参考如下方法:

thread.start_new_thread 函数真的很底层,并没有给你很多控制权。查看 threading 模块,更具体地说是 Thread 类:http://docs.python.org/2/library/threading.html#thread-objects

然后您想要将脚本的最后两行替换为:

# This line should be at the top of your file, obviously :p 
from threading import Thread  
 
threads = [] 
for i in sites: 
    t = Thread(target=ftpconnect, args=[i]) 
    threads.append(t) 
    t.start() 
 
# Wait for all the threads to complete before exiting the program. 
for t in threads: 
    t.join() 

顺便说一下,您的代码失败了,因为在您的 for 循环中,您正在调用 ftpconnect(i),等待它完成,并且 然后尝试使用它的返回值(即None)来启动一个新线程,这显然是行不通的。

一般来说,启动一个线程是通过给它一个可调用对象(函数/方法——你想要可调用对象,不是调用的结果——my_function,而不是 my_function()),以及提供可调用对象的可选参数(在我们的例子中,[i] 因为 ftpconnect 需要一个位置参数,你希望它是 i),然后调用 Thread 对象的 start 方法。