[tor-commits] [stem/master] Convert all except clauses to new grammar
atagar at torproject.org
atagar at torproject.org
Mon May 6 01:09:36 UTC 2013
commit 113f8c14723db3df5dacc02c5efaf54aeca6e688
Author: Sean Robinson <seankrobinson at gmail.com>
Date: Thu May 2 16:29:18 2013 -0700
Convert all except clauses to new grammar
Use the try..except...as grammar available in Python 2.6/2.7 and required
in Python 3.
Signed-off-by: Sean Robinson <seankrobinson at gmail.com>
---
docs/republish.py | 4 +-
docs/tutorials/to_russia_with_love.rst | 2 +-
run_tests.py | 8 +++---
stem/connection.py | 46 +++++++++++++++---------------
stem/control.py | 42 ++++++++++++++--------------
stem/descriptor/__init__.py | 2 +-
stem/descriptor/extrainfo_descriptor.py | 8 +++---
stem/descriptor/networkstatus.py | 2 +-
stem/descriptor/reader.py | 16 +++++-----
stem/descriptor/router_status_entry.py | 4 +-
stem/descriptor/server_descriptor.py | 2 +-
stem/response/events.py | 4 +-
stem/response/protocolinfo.py | 2 +-
stem/socket.py | 14 +++++-----
stem/util/conf.py | 2 +-
stem/util/proc.py | 6 ++--
stem/util/system.py | 2 +-
stem/version.py | 4 +-
test/integ/connection/authentication.py | 2 +-
test/integ/control/controller.py | 8 +++---
test/network.py | 4 +-
test/runner.py | 10 +++---
test/unit/response/getconf.py | 2 +-
test/unit/response/getinfo.py | 2 +-
test/util.py | 2 +-
25 files changed, 100 insertions(+), 100 deletions(-)
diff --git a/docs/republish.py b/docs/republish.py
index ae783cf..ccb6234 100644
--- a/docs/republish.py
+++ b/docs/republish.py
@@ -55,7 +55,7 @@ def republish_site():
if __name__ == '__main__':
try:
opts = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED)[0]
- except getopt.GetoptError, exc:
+ except getopt.GetoptError as exc:
print "%s (for usage provide --help)" % exc
sys.exit(1)
@@ -83,7 +83,7 @@ if __name__ == '__main__':
try:
latest_run = time.time()
republish_site()
- except OSError, exc:
+ except OSError as exc:
LOGGER.log(logging.WARN, str(exc))
else:
republish_site()
diff --git a/docs/tutorials/to_russia_with_love.rst b/docs/tutorials/to_russia_with_love.rst
index 86a9349..a2e9647 100644
--- a/docs/tutorials/to_russia_with_love.rst
+++ b/docs/tutorials/to_russia_with_love.rst
@@ -41,7 +41,7 @@ In the following example we're using stem to `start Tor <../api/process.html>`_,
try:
query.perform()
return output.getvalue()
- except pycurl.error, exc:
+ except pycurl.error as exc:
return "Unable to reach %s (%s)" % (url, exc)
# Start an instance of tor configured to only exit through Russia. This prints
diff --git a/run_tests.py b/run_tests.py
index 41fa2b3..1e76738 100755
--- a/run_tests.py
+++ b/run_tests.py
@@ -81,7 +81,7 @@ def main():
try:
stem.prereq.check_requirements()
- except ImportError, exc:
+ except ImportError as exc:
println("%s\n" % exc)
sys.exit(1)
@@ -90,10 +90,10 @@ def main():
try:
args = _get_args(sys.argv[1:])
- except getopt.GetoptError, exc:
+ except getopt.GetoptError as exc:
println("%s (for usage provide --help)" % exc)
sys.exit(1)
- except ValueError, exc:
+ except ValueError as exc:
println(str(exc))
sys.exit(1)
@@ -205,7 +205,7 @@ def main():
except KeyboardInterrupt:
println(" aborted starting tor: keyboard interrupt\n", ERROR)
break
- except ValueError, exc:
+ except ValueError as exc:
# can arise if get_torrc_entries() runs into a bad settings.cfg data
println(exc, ERROR)
diff --git a/stem/connection.py b/stem/connection.py
index 54404e7..b90b33a 100644
--- a/stem/connection.py
+++ b/stem/connection.py
@@ -23,7 +23,7 @@ fine-grained control over the authentication process. For instance...
try:
control_socket = stem.socket.ControlPort(port = 9051)
- except stem.SocketError, exc:
+ except stem.SocketError as exc:
print "Unable to connect to port 9051 (%s)" % exc
sys.exit(1)
@@ -41,7 +41,7 @@ fine-grained control over the authentication process. For instance...
except stem.connection.PasswordAuthFailed:
print "Unable to authenticate, password is incorrect"
sys.exit(1)
- except stem.connection.AuthenticationFailure, exc:
+ except stem.connection.AuthenticationFailure as exc:
print "Unable to authenticate: %s" % exc
sys.exit(1)
@@ -142,7 +142,7 @@ def connect_port(address = "127.0.0.1", port = 9051, password = None, chroot_pat
try:
control_port = stem.socket.ControlPort(address, port)
- except stem.SocketError, exc:
+ except stem.SocketError as exc:
print exc
return None
@@ -165,7 +165,7 @@ def connect_socket_file(path = "/var/run/tor/control", password = None, chroot_p
try:
control_socket = stem.socket.ControlSocketFile(path)
- except stem.SocketError, exc:
+ except stem.SocketError as exc:
print exc
return None
@@ -202,7 +202,7 @@ def _connect(control_socket, password, chroot_path, controller):
return None
return _connect(control_socket, password, chroot_path, controller)
- except AuthenticationFailure, exc:
+ except AuthenticationFailure as exc:
control_socket.close()
print "Unable to authenticate: %s" % exc
return None
@@ -322,7 +322,7 @@ def authenticate(controller, password = None, chroot_path = None, protocolinfo_r
protocolinfo_response = get_protocolinfo(controller)
except stem.ProtocolError:
raise IncorrectSocketType("unable to use the control socket")
- except stem.SocketError, exc:
+ except stem.SocketError as exc:
raise AuthenticationFailure("socket connection failed (%s)" % exc)
auth_methods = list(protocolinfo_response.auth_methods)
@@ -381,28 +381,28 @@ def authenticate(controller, password = None, chroot_path = None, protocolinfo_r
authenticate_cookie(controller, cookie_path, False)
return # success!
- except OpenAuthRejected, exc:
+ except OpenAuthRejected as exc:
auth_exceptions.append(exc)
- except IncorrectPassword, exc:
+ except IncorrectPassword as exc:
auth_exceptions.append(exc)
- except PasswordAuthRejected, exc:
+ except PasswordAuthRejected as exc:
# Since the PROTOCOLINFO says password auth is available we can assume
# that if PasswordAuthRejected is raised it's being raised in error.
log.debug("The authenticate_password method raised a PasswordAuthRejected when password auth should be available. Stem may need to be corrected to recognize this response: %s" % exc)
auth_exceptions.append(IncorrectPassword(str(exc)))
- except AuthSecurityFailure, exc:
+ except AuthSecurityFailure as exc:
log.info("Tor failed to provide the nonce expected for safecookie authentication. (%s)" % exc)
auth_exceptions.append(exc)
- except (InvalidClientNonce, UnrecognizedAuthChallengeMethod, AuthChallengeFailed), exc:
+ except (InvalidClientNonce, UnrecognizedAuthChallengeMethod, AuthChallengeFailed) as exc:
auth_exceptions.append(exc)
- except (IncorrectCookieSize, UnreadableCookieFile, IncorrectCookieValue), exc:
+ except (IncorrectCookieSize, UnreadableCookieFile, IncorrectCookieValue) as exc:
auth_exceptions.append(exc)
- except CookieAuthRejected, exc:
+ except CookieAuthRejected as exc:
auth_func = "authenticate_safecookie" if exc.is_safecookie else "authenticate_cookie"
log.debug("The %s method raised a CookieAuthRejected when cookie auth should be available. Stem may need to be corrected to recognize this response: %s" % (auth_func, exc))
auth_exceptions.append(IncorrectCookieValue(str(exc), exc.cookie_path, exc.is_safecookie))
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
auth_exceptions.append(AuthenticationFailure(str(exc)))
# All authentication attempts failed. Raise the exception that takes priority
@@ -454,7 +454,7 @@ def authenticate_none(controller, suppress_ctl_errors = True):
pass
raise OpenAuthRejected(str(auth_response), auth_response)
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
try:
controller.connect()
except:
@@ -524,7 +524,7 @@ def authenticate_password(controller, password, suppress_ctl_errors = True):
raise IncorrectPassword(str(auth_response), auth_response)
else:
raise PasswordAuthRejected(str(auth_response), auth_response)
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
try:
controller.connect()
except:
@@ -614,7 +614,7 @@ def authenticate_cookie(controller, cookie_path, suppress_ctl_errors = True):
raise IncorrectCookieValue(str(auth_response), cookie_path, False, auth_response)
else:
raise CookieAuthRejected(str(auth_response), cookie_path, False, auth_response)
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
try:
controller.connect()
except:
@@ -711,7 +711,7 @@ def authenticate_safecookie(controller, cookie_path, suppress_ctl_errors = True)
raise CookieAuthRejected(authchallenge_response_str, cookie_path, True)
else:
raise AuthChallengeFailed(authchallenge_response, cookie_path)
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
try:
controller.connect()
except:
@@ -724,7 +724,7 @@ def authenticate_safecookie(controller, cookie_path, suppress_ctl_errors = True)
try:
stem.response.convert("AUTHCHALLENGE", authchallenge_response)
- except stem.ProtocolError, exc:
+ except stem.ProtocolError as exc:
if not suppress_ctl_errors:
raise exc
else:
@@ -743,7 +743,7 @@ def authenticate_safecookie(controller, cookie_path, suppress_ctl_errors = True)
cookie_data + client_nonce + authchallenge_response.server_nonce)
auth_response = _msg(controller, "AUTHENTICATE %s" % stem.util.str_tools._to_unicode(binascii.b2a_hex(client_hash)))
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
try:
controller.connect()
except:
@@ -810,7 +810,7 @@ def get_protocolinfo(controller):
try:
protocolinfo_response = _msg(controller, "PROTOCOLINFO 1")
- except stem.SocketClosed, exc:
+ except stem.SocketClosed as exc:
raise stem.SocketError(exc)
stem.response.convert("PROTOCOLINFO", protocolinfo_response)
@@ -888,7 +888,7 @@ def _read_cookie(cookie_path, is_safecookie):
try:
with open(cookie_path, 'rb', 0) as f:
return f.read()
- except IOError, exc:
+ except IOError as exc:
exc_msg = "Authentication failed: unable to read '%s' (%s)" % (cookie_path, exc)
raise UnreadableCookieFile(exc_msg, cookie_path, is_safecookie)
@@ -914,7 +914,7 @@ def _expand_cookie_path(protocolinfo_response, pid_resolver, pid_resolution_arg)
raise IOError("cwd lookup failed")
cookie_path = stem.util.system.expand_path(cookie_path, tor_cwd)
- except IOError, exc:
+ except IOError as exc:
resolver_labels = {
stem.util.system.get_pid_by_name: " by name",
stem.util.system.get_pid_by_port: " by port",
diff --git a/stem/control.py b/stem/control.py
index aed45ad..6a7b0ed 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -334,7 +334,7 @@ class BaseController(object):
self._post_authentication()
return response
- except stem.SocketClosed, exc:
+ except stem.SocketClosed as exc:
# If the recv() thread caused the SocketClosed then we could still be
# in the process of closing. Calling close() here so that we can
# provide an assurance to the caller that when we raise a SocketClosed
@@ -583,7 +583,7 @@ class BaseController(object):
else:
# response to a msg() call
self._reply_queue.put(control_message)
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
# Assume that all exceptions belong to the reader. This isn't always
# true, but the msg() call can do a better job of sorting it out.
#
@@ -786,7 +786,7 @@ class Controller(BaseController):
return reply
else:
return reply.values()[0]
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
# bump geoip failure count if...
# * we're caching results
# * this was soley a geoip lookup
@@ -832,7 +832,7 @@ class Controller(BaseController):
self._request_cache["version"] = version
return self._request_cache["version"]
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -876,7 +876,7 @@ class Controller(BaseController):
self._request_cache["exit_policy"] = stem.exit_policy.get_config_policy(policy)
return self._request_cache["exit_policy"]
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -928,7 +928,7 @@ class Controller(BaseController):
raise stem.ProtocolError("Invalid port for a SOCKS listener: %s" % port)
return [(addr, int(port)) for (addr, port) in proxy_addrs]
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -955,7 +955,7 @@ class Controller(BaseController):
try:
return stem.connection.get_protocolinfo(self)
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -990,7 +990,7 @@ class Controller(BaseController):
desc_content = self.get_info(query)
return stem.descriptor.microdescriptor.Microdescriptor(str_tools._to_bytes(desc_content))
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1018,7 +1018,7 @@ class Controller(BaseController):
try:
try:
data_directory = self.get_conf("DataDirectory")
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
raise stem.OperationFailed(message = "Unable to determine the data directory (%s)" % exc)
cached_descriptor_path = os.path.join(data_directory, "cached-microdescs")
@@ -1037,7 +1037,7 @@ class Controller(BaseController):
raise stem.OperationFailed(message = "BUG: Descriptor reader provided non-microdescriptor content (%s)" % type(desc))
yield desc
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1079,7 +1079,7 @@ class Controller(BaseController):
desc_content = self.get_info(query)
return stem.descriptor.server_descriptor.RelayDescriptor(str_tools._to_bytes(desc_content))
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1115,7 +1115,7 @@ class Controller(BaseController):
for desc in stem.descriptor.server_descriptor._parse_file(io.BytesIO(str_tools._to_bytes(desc_content))):
yield desc
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1153,7 +1153,7 @@ class Controller(BaseController):
desc_content = self.get_info(query)
return stem.descriptor.router_status_entry.RouterStatusEntryV2(str_tools._to_bytes(desc_content))
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1190,7 +1190,7 @@ class Controller(BaseController):
for desc in desc_iterator:
yield desc
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1345,7 +1345,7 @@ class Controller(BaseController):
log.debug("GETCONF %s (runtime: %0.4f)" % (" ".join(lookup_params), time.time() - start_time))
return self._get_conf_dict_to_response(reply, default, multiple)
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
log.debug("GETCONF %s (failed: %s)" % (" ".join(lookup_params), exc))
if default != UNDEFINED:
@@ -1730,7 +1730,7 @@ class Controller(BaseController):
return circ
raise ValueError("Tor presently does not have a circuit with the id of '%s'" % circuit_id)
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1757,7 +1757,7 @@ class Controller(BaseController):
circuits.append(circ_message)
return circuits
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -1945,7 +1945,7 @@ class Controller(BaseController):
streams.append(message)
return streams
- except Exception, exc:
+ except Exception as exc:
if default == UNDEFINED:
raise exc
else:
@@ -2088,7 +2088,7 @@ class Controller(BaseController):
logging_id = "stem.controller.event_reattach-%s" % "-".join(failed_events)
log.log_once(logging_id, log.WARN, "We were unable to re-attach our event listeners to the new tor instance for: %s" % ", ".join(failed_events))
- except stem.ProtocolError, exc:
+ except stem.ProtocolError as exc:
log.warn("Unable to issue the SETEVENTS request to re-attach our listeners (%s)" % exc)
# issue TAKEOWNERSHIP if we're the owning process for this tor instance
@@ -2105,7 +2105,7 @@ class Controller(BaseController):
try:
self.reset_conf("__OwningControllerProcess")
- except stem.ControllerError, exc:
+ except stem.ControllerError as exc:
log.warn("We were unable to reset tor's __OwningControllerProcess configuration. It will continue to periodically check if our pid exists. (%s)" % exc)
else:
log.warn("We were unable assert ownership of tor through TAKEOWNERSHIP, despite being configured to be the owning process through __OwningControllerProcess. (%s)" % response)
@@ -2199,7 +2199,7 @@ def _parse_circ_path(path):
if path:
try:
return [_parse_circ_entry(entry) for entry in path.split(',')]
- except stem.ProtocolError, exc:
+ except stem.ProtocolError as exc:
# include the path with the exception
raise stem.ProtocolError("%s: %s" % (exc, path))
else:
diff --git a/stem/descriptor/__init__.py b/stem/descriptor/__init__.py
index ef438a7..2567a4b 100644
--- a/stem/descriptor/__init__.py
+++ b/stem/descriptor/__init__.py
@@ -522,7 +522,7 @@ def _get_descriptor_components(raw_contents, validate, extra_keywords = ()):
try:
block_contents = _get_pseudo_pgp_block(remaining_lines)
- except ValueError, exc:
+ except ValueError as exc:
if not validate:
continue
diff --git a/stem/descriptor/extrainfo_descriptor.py b/stem/descriptor/extrainfo_descriptor.py
index 5e6ddd0..e9aea30 100644
--- a/stem/descriptor/extrainfo_descriptor.py
+++ b/stem/descriptor/extrainfo_descriptor.py
@@ -597,7 +597,7 @@ class ExtraInfoDescriptor(stem.descriptor.Descriptor):
self.dir_v2_share = percentage
elif keyword == "dirreq-v3-share":
self.dir_v3_share = percentage
- except ValueError, exc:
+ except ValueError as exc:
if validate:
raise ValueError("Value can't be parsed as a percentage: %s" % line)
elif keyword in ("cell-processed-cells", "cell-queued-cells", "cell-time-in-queue"):
@@ -656,7 +656,7 @@ class ExtraInfoDescriptor(stem.descriptor.Descriptor):
elif keyword == "dirreq-stats-end":
self.dir_stats_end = timestamp
self.dir_stats_interval = interval
- except ValueError, exc:
+ except ValueError as exc:
if validate:
raise exc
elif keyword == "conn-bi-direct":
@@ -676,7 +676,7 @@ class ExtraInfoDescriptor(stem.descriptor.Descriptor):
self.conn_bi_direct_read = int(stats[1])
self.conn_bi_direct_write = int(stats[2])
self.conn_bi_direct_both = int(stats[3])
- except ValueError, exc:
+ except ValueError as exc:
if validate:
raise exc
elif keyword in ("read-history", "write-history", "dirreq-read-history", "dirreq-write-history"):
@@ -707,7 +707,7 @@ class ExtraInfoDescriptor(stem.descriptor.Descriptor):
self.dir_write_history_end = timestamp
self.dir_write_history_interval = interval
self.dir_write_history_values = history_values
- except ValueError, exc:
+ except ValueError as exc:
if validate:
raise exc
elif keyword in ("exit-kibibytes-written", "exit-kibibytes-read", "exit-streams-opened"):
diff --git a/stem/descriptor/networkstatus.py b/stem/descriptor/networkstatus.py
index bad31d4..1081b10 100644
--- a/stem/descriptor/networkstatus.py
+++ b/stem/descriptor/networkstatus.py
@@ -956,7 +956,7 @@ def _parse_int_mappings(keyword, value, validate):
results[entry_key] = entry_value
seen_keys.append(entry_key)
- except ValueError, exc:
+ except ValueError as exc:
if not validate:
continue
diff --git a/stem/descriptor/reader.py b/stem/descriptor/reader.py
index d764ef6..18da11f 100644
--- a/stem/descriptor/reader.py
+++ b/stem/descriptor/reader.py
@@ -216,7 +216,7 @@ def save_processed_files(path, processed_files):
if not os.path.exists(path_dir):
os.makedirs(path_dir)
- except OSError, exc:
+ except OSError as exc:
raise IOError(exc)
with open(path, "w") as output_file:
@@ -461,7 +461,7 @@ class DescriptorReader(object):
last_modified = int(os.stat(target).st_mtime)
last_used = self._processed_files.get(target)
new_processed_files[target] = last_modified
- except OSError, exc:
+ except OSError as exc:
self._notify_skip_listeners(target, ReadFailed(exc))
return
@@ -515,11 +515,11 @@ class DescriptorReader(object):
self._unreturned_descriptors.put(desc)
self._iter_notice.set()
- except TypeError, exc:
+ except TypeError as exc:
self._notify_skip_listeners(target, UnrecognizedType(mime_type))
- except ValueError, exc:
+ except ValueError as exc:
self._notify_skip_listeners(target, ParsingFailure(exc))
- except IOError, exc:
+ except IOError as exc:
self._notify_skip_listeners(target, ReadFailed(exc))
def _handle_archive(self, target):
@@ -546,13 +546,13 @@ class DescriptorReader(object):
desc._set_archive_path(entry.name)
self._unreturned_descriptors.put(desc)
self._iter_notice.set()
- except TypeError, exc:
+ except TypeError as exc:
self._notify_skip_listeners(target, ParsingFailure(exc))
- except ValueError, exc:
+ except ValueError as exc:
self._notify_skip_listeners(target, ParsingFailure(exc))
finally:
entry.close()
- except IOError, exc:
+ except IOError as exc:
self._notify_skip_listeners(target, ReadFailed(exc))
finally:
if tar_file:
diff --git a/stem/descriptor/router_status_entry.py b/stem/descriptor/router_status_entry.py
index 12f1c7f..076baab 100644
--- a/stem/descriptor/router_status_entry.py
+++ b/stem/descriptor/router_status_entry.py
@@ -579,7 +579,7 @@ def _parse_v_line(desc, value, validate):
if value.startswith("Tor "):
try:
desc.version = stem.version.Version(value[4:])
- except ValueError, exc:
+ except ValueError as exc:
if validate:
raise ValueError("%s has a malformed tor version (%s): v %s" % (desc._name(), exc, value))
@@ -639,7 +639,7 @@ def _parse_p_line(desc, value, validate):
try:
desc.exit_policy = stem.exit_policy.MicroExitPolicy(value)
- except ValueError, exc:
+ except ValueError as exc:
if not validate:
return
diff --git a/stem/descriptor/server_descriptor.py b/stem/descriptor/server_descriptor.py
index d2efc0b..4af4976 100644
--- a/stem/descriptor/server_descriptor.py
+++ b/stem/descriptor/server_descriptor.py
@@ -561,7 +561,7 @@ class ServerDescriptor(stem.descriptor.Descriptor):
self.write_history_end = timestamp
self.write_history_interval = interval
self.write_history_values = history_values
- except ValueError, exc:
+ except ValueError as exc:
if validate:
raise exc
else:
diff --git a/stem/response/events.py b/stem/response/events.py
index d9e3493..b6badd6 100644
--- a/stem/response/events.py
+++ b/stem/response/events.py
@@ -357,7 +357,7 @@ class CircuitEvent(Event):
if self.created is not None:
try:
self.created = str_tools._parse_iso_timestamp(self.created)
- except ValueError, exc:
+ except ValueError as exc:
raise stem.ProtocolError("Unable to parse create date (%s): %s" % (exc, self))
if not tor_tools.is_valid_circuit_id(self.id):
@@ -413,7 +413,7 @@ class CircMinorEvent(Event):
if self.created is not None:
try:
self.created = str_tools._parse_iso_timestamp(self.created)
- except ValueError, exc:
+ except ValueError as exc:
raise stem.ProtocolError("Unable to parse create date (%s): %s" % (exc, self))
if not tor_tools.is_valid_circuit_id(self.id):
diff --git a/stem/response/protocolinfo.py b/stem/response/protocolinfo.py
index 8f8c27c..b4f7453 100644
--- a/stem/response/protocolinfo.py
+++ b/stem/response/protocolinfo.py
@@ -113,7 +113,7 @@ class ProtocolInfoResponse(stem.response.ControlMessage):
try:
self.tor_version = stem.version.Version(line.pop_mapping(True)[1])
- except ValueError, exc:
+ except ValueError as exc:
raise stem.ProtocolError(exc)
else:
log.debug("Unrecognized PROTOCOLINFO line type '%s', ignoring it: %s" % (line_type, line))
diff --git a/stem/socket.py b/stem/socket.py
index 0cd4b0d..bfe5839 100644
--- a/stem/socket.py
+++ b/stem/socket.py
@@ -85,7 +85,7 @@ class ControlSocket(object):
raise stem.SocketClosed()
send_message(self._socket_file, message, raw)
- except stem.SocketClosed, exc:
+ except stem.SocketClosed as exc:
# if send_message raises a SocketClosed then we should properly shut
# everything down
@@ -117,7 +117,7 @@ class ControlSocket(object):
raise stem.SocketClosed()
return recv_message(socket_file)
- except stem.SocketClosed, exc:
+ except stem.SocketClosed as exc:
# If recv_message raises a SocketClosed then we should properly shut
# everything down. However, there's a couple cases where this will
# cause deadlock...
@@ -340,7 +340,7 @@ class ControlPort(ControlSocket):
control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
control_socket.connect((self._control_addr, self._control_port))
return control_socket
- except socket.error, exc:
+ except socket.error as exc:
raise stem.SocketError(exc)
@@ -384,7 +384,7 @@ class ControlSocketFile(ControlSocket):
control_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
control_socket.connect(self._socket_path)
return control_socket
- except socket.error, exc:
+ except socket.error as exc:
raise stem.SocketError(exc)
@@ -429,7 +429,7 @@ def send_message(control_file, message, raw = False):
log_message = message.replace("\r\n", "\n").rstrip()
log.trace("Sent to tor:\n" + log_message)
- except socket.error, exc:
+ except socket.error as exc:
log.info("Failed to send message: %s" % exc)
# When sending there doesn't seem to be a reliable method for
@@ -480,7 +480,7 @@ def recv_message(control_file):
prefix = logging_prefix % "SocketClosed"
log.info(prefix + "socket file has been closed")
raise stem.SocketClosed("socket file has been closed")
- except (socket.error, ValueError), exc:
+ except (socket.error, ValueError) as exc:
# When disconnected we get...
#
# Python 2:
@@ -542,7 +542,7 @@ def recv_message(control_file):
if stem.prereq.is_python_3():
line = stem.util.str_tools._to_unicode(line)
- except socket.error, exc:
+ except socket.error as exc:
prefix = logging_prefix % "SocketClosed"
log.info(prefix + "received an exception while mid-way through a data reply (exception: \"%s\", read content: \"%s\")" % (exc, log.escape(raw_content)))
raise stem.SocketClosed(exc)
diff --git a/stem/util/conf.py b/stem/util/conf.py
index eaad09b..14cc306 100644
--- a/stem/util/conf.py
+++ b/stem/util/conf.py
@@ -357,7 +357,7 @@ class Config(object):
try:
user_config.load("/home/atagar/myConfig")
- except IOError, exc:
+ except IOError as exc:
print "Unable to load the user's config: %s" % exc
# This replace the contents of ssh_config with the values from the user's
diff --git a/stem/util/proc.py b/stem/util/proc.py
index e165b89..e399b84 100644
--- a/stem/util/proc.py
+++ b/stem/util/proc.py
@@ -360,11 +360,11 @@ def get_connections(pid):
conn.append((local_ip, local_port, foreign_ip, foreign_port))
proc_file.close()
- except IOError, exc:
+ except IOError as exc:
exc = IOError("unable to read '%s': %s" % (proc_file_path, exc))
_log_failure(parameter, exc)
raise exc
- except Exception, exc:
+ except Exception as exc:
exc = IOError("unable to parse '%s': %s" % (proc_file_path, exc))
_log_failure(parameter, exc)
raise exc
@@ -465,7 +465,7 @@ def _get_lines(file_path, line_prefixes, parameter):
raise IOError(msg)
else:
return results
- except IOError, exc:
+ except IOError as exc:
_log_failure(parameter, exc)
raise exc
diff --git a/stem/util/system.py b/stem/util/system.py
index bea6222..645fbbe 100644
--- a/stem/util/system.py
+++ b/stem/util/system.py
@@ -681,7 +681,7 @@ def call(command, default = UNDEFINED):
return stdout.decode("utf-8", "replace").splitlines()
else:
return []
- except OSError, exc:
+ except OSError as exc:
log.debug("System call (failed): %s (error: %s)" % (command, exc))
if default != UNDEFINED:
diff --git a/stem/version.py b/stem/version.py
index cef5487..d218ffb 100644
--- a/stem/version.py
+++ b/stem/version.py
@@ -82,7 +82,7 @@ def get_system_tor_version(tor_cmd = "tor"):
try:
version_output = stem.util.system.call(version_cmd)
- except OSError, exc:
+ except OSError as exc:
# make the error message nicer if this is due to tor being unavialable
if "No such file or directory" in str(exc):
@@ -104,7 +104,7 @@ def get_system_tor_version(tor_cmd = "tor"):
try:
version_str = last_line[12:-1]
VERSION_CACHE[tor_cmd] = Version(version_str)
- except ValueError, exc:
+ except ValueError as exc:
raise IOError(exc)
else:
raise IOError("Unexpected response from '%s': %s" % (version_cmd, last_line))
diff --git a/test/integ/connection/authentication.py b/test/integ/connection/authentication.py
index 438fca7..72ed40a 100644
--- a/test/integ/connection/authentication.py
+++ b/test/integ/connection/authentication.py
@@ -400,7 +400,7 @@ class TestAuthenticate(unittest.TestCase):
stem.connection.authenticate_safecookie(control_socket, auth_arg)
test.runner.exercise_controller(self, control_socket)
- except stem.connection.AuthenticationFailure, exc:
+ except stem.connection.AuthenticationFailure as exc:
# authentication functions should re-attach on failure
self.assertTrue(control_socket.is_alive())
diff --git a/test/integ/control/controller.py b/test/integ/control/controller.py
index 64cbaa4..a89d9be 100644
--- a/test/integ/control/controller.py
+++ b/test/integ/control/controller.py
@@ -475,7 +475,7 @@ class TestController(unittest.TestCase):
try:
controller.set_conf("invalidkeyboo", "abcde")
self.fail()
- except stem.InvalidArguments, exc:
+ except stem.InvalidArguments as exc:
self.assertEqual(["invalidkeyboo"], exc.arguments)
# resets configuration parameters
@@ -499,7 +499,7 @@ class TestController(unittest.TestCase):
"bombay": "vadapav",
})
self.fail()
- except stem.InvalidArguments, exc:
+ except stem.InvalidArguments as exc:
self.assertEqual(["bombay"], exc.arguments)
# context-sensitive keys (the only retched things for which order matters)
@@ -544,7 +544,7 @@ class TestController(unittest.TestCase):
try:
controller.load_conf("Blahblah blah")
self.fail()
- except stem.InvalidArguments, exc:
+ except stem.InvalidArguments as exc:
self.assertEqual(["Blahblah"], exc.arguments)
# valid config
@@ -617,7 +617,7 @@ class TestController(unittest.TestCase):
try:
controller.enable_feature(["NOT", "A", "FEATURE"])
- except stem.InvalidArguments, exc:
+ except stem.InvalidArguments as exc:
self.assertEqual(["NOT"], exc.arguments)
else:
self.fail()
diff --git a/test/network.py b/test/network.py
index df9f018..2dc7270 100644
--- a/test/network.py
+++ b/test/network.py
@@ -289,7 +289,7 @@ def external_ip(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, int(port)))
- except Exception, exc:
+ except Exception as exc:
raise SocketError("Failed to connect to the socks server: " + str(exc))
try:
@@ -300,7 +300,7 @@ def external_ip(host, port):
# everything after the blank line is the 'data' in a HTTP response
# The response data for our request for request should be an IP address + '\n'
return response[response.find("\r\n\r\n"):].strip()
- except Exception, exc:
+ except Exception as exc:
return None
diff --git a/test/runner.py b/test/runner.py
index 9e4ec83..0ea840a 100644
--- a/test/runner.py
+++ b/test/runner.py
@@ -326,7 +326,7 @@ class Runner(object):
# revert our cwd back to normal
if Target.RELATIVE in self.attribute_targets:
os.chdir(original_cwd)
- except OSError, exc:
+ except OSError as exc:
raise exc
def stop(self):
@@ -615,7 +615,7 @@ class Runner(object):
else:
os.makedirs(self._test_dir)
println("done", STATUS)
- except OSError, exc:
+ except OSError as exc:
test.output.print_error("failed (%s)" % exc)
raise exc
@@ -636,7 +636,7 @@ class Runner(object):
os.chmod(socket_dir, 0700)
println("done", STATUS)
- except OSError, exc:
+ except OSError as exc:
test.output.print_error("failed (%s)" % exc)
raise exc
@@ -677,7 +677,7 @@ class Runner(object):
println(" %s" % line.strip(), SUBSTATUS)
println()
- except Exception, exc:
+ except Exception as exc:
test.output.print_error("failed (%s)\n" % exc)
raise OSError(exc)
@@ -707,6 +707,6 @@ class Runner(object):
runtime = time.time() - start_time
println(" done (%i seconds)\n" % runtime, STATUS)
- except OSError, exc:
+ except OSError as exc:
test.output.print_error(" failed to start tor: %s\n" % exc)
raise exc
diff --git a/test/unit/response/getconf.py b/test/unit/response/getconf.py
index 2e199ab..de7beb5 100644
--- a/test/unit/response/getconf.py
+++ b/test/unit/response/getconf.py
@@ -102,7 +102,7 @@ class TestGetConfResponse(unittest.TestCase):
try:
stem.response.convert("GETCONF", control_message)
- except stem.InvalidArguments, exc:
+ except stem.InvalidArguments as exc:
self.assertEqual(exc.arguments, ["brickroad", "submarine"])
def test_invalid_content(self):
diff --git a/test/unit/response/getinfo.py b/test/unit/response/getinfo.py
index 92326c8..b6d2c8d 100644
--- a/test/unit/response/getinfo.py
+++ b/test/unit/response/getinfo.py
@@ -125,7 +125,7 @@ class TestGetInfoResponse(unittest.TestCase):
try:
stem.response.convert("GETINFO", control_message)
- except stem.InvalidArguments, exc:
+ except stem.InvalidArguments as exc:
self.assertEqual(exc.arguments, ["blackhole"])
def test_invalid_multiline_content(self):
diff --git a/test/util.py b/test/util.py
index dbd776f..10a5459 100644
--- a/test/util.py
+++ b/test/util.py
@@ -586,7 +586,7 @@ class Task(object):
if isinstance(result, (list, tuple)):
for line in result:
println(" %s" % line, STATUS)
- except Exception, exc:
+ except Exception as exc:
output_msg = str(exc)
if not output_msg or self.is_required:
More information about the tor-commits
mailing list