Python 多线程

标签 python multithreading

我需要从 ip 列表中提取所有 url, 我写了这个 python 脚本,但我在多次提取相同的 ip 时遇到问题(更多线程是使用相同的 ip 创建的)。 谁能使用多线程改进我的解决方案?

对不起我的英语 谢谢大家

import urllib2, os, re, sys, os, time, httplib, thread, argparse, random

try:
    ListaIP = open(sys.argv[1], "r").readlines()
except(IOError): 
    print "Error: Check your IP list path\n"
    sys.exit(1)



def getIP():
    if len(ListaIP) != 0:
        value = random.sample(ListaIP,  1)
        ListaIP.remove(value[0])
        return value
    else:
        print "\nListaIPs sa terminat\n"
        sys.exit(1)

def extractURL(ip):
    print ip + '\n'
    page = urllib2.urlopen('http://sameip.org/ip/' + ip)
    html = page.read()
    links = re.findall(r'href=[\'"]?([^\'" >]+)', html)
    outfile = open('2.log', 'a')
    outfile.write("\n".join(links))
    outfile.close()

def start():
    while True:
        if len(ListaIP) != 0:
            test = getIP()
            IP = ''.join(test).replace('\n', '')
            extractURL(IP)
        else:
            break


for x in range(0, 10):
    thread.start_new_thread( start, () )

while 1:
    pass

最佳答案

使用threading.Lock。锁应该是全局的,并且在您创建 IP 列表时创建。

lock.acquiregetIP()

的开头

并在您离开该方法之前释放它。

您看到的是,线程 1 执行 value=random.sample,然后线程 2 也在 之前执行 value=random.sample > 线程 1 到达 remove。所以当线程 2 到达那里时,该项目仍在列表中。 因此,两个线程都有机会获得相同的 IP。

关于Python 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917311/

相关文章:

java - 游戏循环帧独立

multithreading - 如何在nodejs中创建线程

python - 复制 pandas 数据框和系列

python - 如何在 Python 的请求中使用 FTP

使用点表示法的 Python 导入无法按预期工作

java - 我如何构建多线程代码以更好地重用java中的代码?

python - 如何在 MySQL 中查找重复项

python - 为什么欧氏距离在这里不起作用?

arrays - Swift 可变数组线程安全

python - Twiss SSH 多个同时命令