Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

twitter - Can an except block of python have 2 conditions simultaneously?

I was trying to learn stock prediction with the help of this github project. but when I run the main.py file given in the repository, via the cmd. I encountered an error

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

The below given code is part of a PyPi module named tweetstreami.e. named as tweetstream/streamclasses.py. Which while implementing in a Twitter sentiment analysis project gave the error

import time
import urllib
import urllib2
import socket
from platform import python_version_tuple
import anyjson

from . 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 ammount 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 usefull 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The second item in the except is an identifier used in the body of the exception to access the exception information. The try/except syntax changed between Python 2 and Python 3 and your code is the Python 2 syntax.

Python 2 (language reference):

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

Python 3 (language reference, rationale):

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

Note that can be a single exception class or a tuple of exception classes to catch more than one type in a single except clause, so to answer your titled question you could use the following to handle more than one possible exception being thrown:

try:
    x = array[5]  # NameError if array doesn't exist, IndexError if it is too short
except (IndexError,NameError) as e:
    print(e)  # which was it?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...