python-3.x - python的except块可以同时有2个条件吗?
问题描述
我试图在这个github 项目的帮助下学习股票预测。但是当我运行main.py
存储库中给出的文件时,通过cmd
. 我遇到了一个错误
File "/Stock-Predictor/src/tweetstream/streamclasses.py", line 101
except urllib2.HTTPError, exception:
^
SyntaxError: invalid syntax
下面给出的代码是一个名为tweetstream
ie的 PyPi 模块的一部分tweetstream/streamclasses.py
。在 Twitter 情绪分析项目中实施时出现错误
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 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>:
...
try:
...
except <expression> as <identifier>:
...
请注意,可以是单个异常类或异常类元组,以在单个子句中捕获多个类型except
,因此要回答您的标题问题,您可以使用以下内容处理多个可能引发的异常:
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?
推荐阅读
- python-3.x - 如何在自定义 keras 层上使用自定义激活
- api - 方法文件返回方法 Illuminate\Http\Response::file 不存在
- python - 要绘制的点不按顺序
- c - 原始类型声明如何在 C 中工作?
- python - 如何忽略根警告?
- django - 我如何在一个引导表 django 2.1 上填充我的数据
- excel - VBA-excel循环文本框
- javascript - 通过使用 javascript 在 HTML 中单击来更改图片服务器的时间
- python - 网页抓取python多个属性(div和id)
- r - 根据可用库存将项目划分为其他 ID