Python的except块可以同时有两个条件吗?

我在尝试通过这个GitHub项目学习股票预测。但是当我在cmd中运行存储库中提供的main.py文件时,遇到了一个错误

File "/Stock-Predictor/src/tweetstream/streamclasses.py", line 101    except urllib2.HTTPError, exception:                            ^SyntaxError: invalid syntax

下面的代码是名为tweetstream的PyPi模块的一部分,即tweetstream/streamclasses.py。在Twitter情感分析项目中实现时出现了错误

import timeimport urllibimport urllib2import socketfrom platform import python_version_tupleimport anyjsonfrom . import AuthenticationError, ConnectionError, USER_AGENT class BaseStream(object):    """A network connection to Twitters streaming API    :param username: Twitter username for the account accessing the API.    :param password: Twitter password for the account accessing the API.    :keyword count: Number of tweets from the past to get before switching to      live stream.    :keyword url: Endpoint URL for the object. Note: you should not      need to edit this. It's present to make testing easier.    .. attribute:: connected        True if the object is currently connected to the stream.    .. attribute:: url        The URL to which the object is connected    .. attribute:: starttime        The timestamp, in seconds since the epoch, the object connected to the        streaming api.    .. attribute:: count        The number of tweets that have been returned by the object.    .. attribute:: rate        The rate at which tweets have been returned from the object as a        float. see also :attr: `rate_period`.    .. attribute:: rate_period        The amount of time to sample tweets to calculate tweet rate. By        default 10 seconds. Changes to this attribute will not be reflected        until the next time the rate is calculated. The rate of tweets vary        with time of day etc. so it's useful to set this to something        sensible.    .. attribute:: user_agent        User agent string that will be included in the request. NOTE: This can        not be changed after the connection has been made. This property must        thus be set before accessing the iterator. The default is set in        :attr: `USER_AGENT`.    """    def __init__(self, username, password, catchup=None, url=None):        self._conn = None        self._rate_ts = None        self._rate_cnt = 0        self._username = username        self._password = password        self._catchup_count = catchup        self._iter = self.__iter__()        self.rate_period = 10  # in seconds        self.connected = False        self.starttime = None        self.count = 0        self.rate = 0        self.user_agent = USER_AGENT        if url: self.url = url    def __enter__(self):        return self    def __exit__(self, *params):        self.close()        return False    def _init_conn(self):        """Open the connection to the twitter server"""        headers = {'User-Agent': self.user_agent}        postdata = self._get_post_data() or {}        if self._catchup_count:            postdata["count"] = self._catchup_count        poststring = urllib.urlencode(postdata) if postdata else None        req = urllib2.Request(self.url, poststring, headers)        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()        password_mgr.add_password(None, self.url, self._username, self._password)        handler = urllib2.HTTPBasicAuthHandler(password_mgr)        opener = urllib2.build_opener(handler)        try:            self._conn = opener.open(req)        except urllib2.HTTPError, exception:  #___________________________problem here            if exception.code == 401:                raise AuthenticationError("Access denied")            elif exception.code == 404:                raise ConnectionError("URL not found: %s" % self.url)            else:  # re raise. No idea what would cause this, so want to know                raise        except urllib2.URLError, exception:            raise ConnectionError(exception.reason)

回答:

except块中的第二个项目是用于访问异常信息的标识符。try/except语法在Python 2和Python 3之间发生了变化,您的代码是Python 2的语法。

Python 2(语言参考):

try:    ...except <expression>, <identifier>:    ...

Python 3(语言参考理由):

try:    ...except <expression> as <identifier>:    ...

请注意,这可以是一个单一的异常类,也可以是一个异常类的元组,用于在一个except子句中捕获多种类型的异常,因此为了回答您标题中的问题,您可以使用以下方法来处理可能抛出的多个异常:

try:    x = array[5]  # 如果array不存在则引发NameError,如果索引过大则引发IndexErrorexcept (IndexError,NameError) as e:    print(e)  # 这是哪种错误?

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注