use*_*554 1 python multithreading
我想了解更多有关线程模块的信息.我想出了一个快速的脚本,但是当我运行它时出现错误.文档显示格式为:
thread.start_new_thread ( function, args[, kwargs] )
Run Code Online (Sandbox Code Playgroud)
我的方法只有一个参数.
#!/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))
Run Code Online (Sandbox Code Playgroud)
我看到的错误发生在for循环的一次迭代之后:
回溯(最近一次调用最后一次):文件"./ftpthread.py",第16行,在thread.start_new_thread(ftpconnect(i)中)TypeError:start_new_thread预期至少有2个参数,得到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'
Run Code Online (Sandbox Code Playgroud)
该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()
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你的代码失败了,因为在你的for循环中,你正在调用ftpconnect(i),等待它完成,然后尝试使用它的返回值(即None)来启动一个新的线程,这显然不起作用.
通常,启动一个线程是通过给它一个可调用的对象(函数/方法 - 你想要可调用的对象,而不是调用的结果my_function,而不是my_function()),以及给出可调用对象的可选参数来完成的(在我们的例子中) ,[i]因为ftpconnect需要一个位置参数,你想要它i,然后调用Thread对象的start方法.