Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何处理Python';线程异常?_Python_Multithreading_Exception Handling_Python Multithreading - Fatal编程技术网

如何处理Python';线程异常?

如何处理Python';线程异常?,python,multithreading,exception-handling,python-multithreading,Python,Multithreading,Exception Handling,Python Multithreading,我正在使用Selenium运行两个Firefox实例并获取详细信息页面。 我使用threading.Thread为每个页面并行加载页面。 我还想使用浏览器设置最大页面加载时间的超时。在我的代码中设置页面加载超时() 我的整个代码如下所示: from selenium import webdriver from threading import Thread from selenium.common.exceptions import TimeoutException class Test()

我正在使用Selenium运行两个Firefox实例并获取详细信息页面。 我使用
threading.Thread
为每个页面并行加载页面。 我还想使用
浏览器设置最大页面加载时间的超时。在我的代码中设置页面加载超时()

我的整个代码如下所示:

from selenium import webdriver
from threading import Thread
from selenium.common.exceptions import TimeoutException


class Test():
        def __init__(self):
            browser = webdriver.Firefox()

            def load_page(browser, url):
                browser.set_page_load_timeout(20)
                browser.get(url)

            t = Thread(target=load_page, args=(browser, 'http://www.stackoverflow.com', ))
            t.start()
            t.join()

if __name__ == '__main__':
    try:
        Test()
    except TimeoutException:
        print "timeout reached"
尽管我的
try-except
声明中有以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Temp\test_b.py", line 13, in load_page
    browser.get(url)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 213, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 181, in check_response
    raise exception_class(message, screen, stacktrace)
TimeoutException: Message: Timed out waiting for page load.
Stacktrace:
    at Utils.initWebLoadingListener/< (file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver-component.js:9010)
    at WebLoadingListener/e (file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver-component.js:5114)
    at WebLoadingListener/< (file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver-component.js:5122)
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver-component.js:621)
线程1中的异常: 回溯(最近一次呼叫最后一次): 文件“C:\Python27\lib\threading.py”,第801行,在引导程序内部 self.run() 文件“C:\Python27\lib\threading.py”,第754行,正在运行 自我目标(*自我参数,**自我参数) 文件“C:\Temp\test\u b.py”,第13行,在加载页面 browser.get(url) 文件“C:\Python27\lib\site packages\selenium\webdriver\remote\webdriver.py”,第213行,在get中 self.execute(Command.GET,{'url':url}) 文件“C:\Python27\lib\site packages\selenium\webdriver\remote\webdriver.py”,第201行,执行 self.error\u handler.check\u响应(响应) 文件“C:\Python27\lib\site packages\selenium\webdriver\remote\errorhandler.py”,第181行,在check\u响应中 引发异常类(消息、屏幕、堆栈跟踪) TimeoutException:消息:等待页面加载时超时。 堆栈跟踪: 在Utils.initWebLoadingListener/<(file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver component.js:9010) 在WebLoadingListener/e上(file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver component.js:5114) 在WebLoadingListener/<(file:///c:/users/mgal/appdata/local/temp/tmpsasxck/extensions/fxdriver@googlecode.com/components/driver component.js:5122)
在fxdriver.Timer.prototype.setTimeout/中,您不能。您应该在线程中处理异常,因此您的函数应该大致类似于:

def load_page(browser, url):
    try:
        browser.set_page_load_timeout(20)
        browser.get(url)
    except TimeoutException:
        '''Handle me here'''
编辑:您实际要求的是:

from selenium import webdriver
from threading import Thread
from Queue import Queue
from selenium.common.exceptions import TimeoutException


class Test():
        def __init__(self, queue, url):
            browser = webdriver.Firefox()

            def load_page(browser, url):
                try:
                    browser.set_page_load_timeout(20)
                    browser.get(url)
                except Exception as e:
                    queue.put(e)
                else:
                    queue.put('OK or whatever the result you want')

            t = Thread(target=load_page, args=(browser, url, ))
            t.start()

if __name__ == '__main__':
    urls = ('http://www.stackoverflow.com', 'http://http://meta.stackoverflow.com/')
    queue = Queue()
    for url in urls:
        Test(queue, url)
    for i in range(len(urls)):
        result = queue.get()
        if isinstance(result, Exception):
            '''Handle exception preferably trying to determine the actual exception type'''
        else:
            '''Say cool cause everything is fine'''

线程子线程在它们自己的堆栈中运行,因此如果没有消息/事件传递,这是不可能的。您可以使用python的
Queue
库(线程安全)将队列对象传递给子函数,并将其用作父函数可以处理的事件池。

您可以在线程中捕获异常,并使用Queue将异常对象传递给主线程。但首先,您的代码没有利用线程,因为您总是在启动线程后立即等待线程加入。这样,您总是会得到比没有线程时性能更差的顺序执行。