Caching for stem.process.get_version()

Caching results of the stem.process.get_version() function to avoid unnecessary
lookups.
This commit is contained in:
Damian Johnson 2011-10-27 09:17:26 -07:00
parent 7766cb79ff
commit 11b2a71d3a

View File

@ -15,6 +15,9 @@ from stem.util import system
# number of seconds before we time out our attempt to start a tor instance
DEFAULT_INIT_TIMEOUT = 90
# cache for the get_version function
VERSION_CACHE = {}
def get_version(tor_cmd = "tor"):
"""
Provides the version of tor.
@ -29,29 +32,32 @@ def get_version(tor_cmd = "tor"):
IOError if unable to query or parse the version
"""
try:
version_cmd = "%s --version" % tor_cmd
version_output = system.call(version_cmd)
except OSError, exc:
raise IOError(exc)
if version_output:
# output example:
# Oct 21 07:19:27.438 [notice] Tor v0.2.1.30. This is experimental software. Do not rely on it for strong anonymity. (Running on Linux i686)
# Tor version 0.2.1.30.
if not tor_cmd in VERSION_CACHE:
try:
version_cmd = "%s --version" % tor_cmd
version_output = system.call(version_cmd)
except OSError, exc:
raise IOError(exc)
last_line = version_output[-1]
if last_line.startswith("Tor version ") and last_line.endswith("."):
try:
version_str = last_line[12:-1]
return stem.types.get_version(version_str)
except ValueError, exc:
raise IOError(exc)
if version_output:
# output example:
# Oct 21 07:19:27.438 [notice] Tor v0.2.1.30. This is experimental software. Do not rely on it for strong anonymity. (Running on Linux i686)
# Tor version 0.2.1.30.
last_line = version_output[-1]
if last_line.startswith("Tor version ") and last_line.endswith("."):
try:
version_str = last_line[12:-1]
VERSION_CACHE[tor_cmd] = stem.types.get_version(version_str)
except ValueError, exc:
raise IOError(exc)
else:
raise IOError("Unexpected response from '%s': %s" % (version_cmd, last_line))
else:
raise IOError("Unexpected response from '%s': %s" % (version_cmd, last_line))
else:
raise IOError("'%s' didn't have any output" % version_cmd)
raise IOError("'%s' didn't have any output" % version_cmd)
return VERSION_CACHE[tor_cmd]
def launch_tor(torrc_path, completion_percent = 100, init_msg_handler = None, timeout = DEFAULT_INIT_TIMEOUT):
"""