本文整理汇总了Python中stem.util.log.debug函数的典型用法代码示例。如果您正苦于以下问题:Python debug函数的具体用法?Python debug怎么用?Python debug使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了debug函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _expand_cookie_path
def _expand_cookie_path(protocolinfo_response, pid_resolver, pid_resolution_arg):
"""
Attempts to expand a relative cookie path with the given pid resolver. This
leaves the cookie_path alone if it's already absolute, **None**, or the
system calls fail.
"""
cookie_path = protocolinfo_response.cookie_path
if cookie_path and not os.path.isabs(cookie_path):
try:
tor_pid = pid_resolver(pid_resolution_arg)
if not tor_pid:
raise IOError('pid lookup failed')
tor_cwd = stem.util.system.cwd(tor_pid)
if not tor_cwd:
raise IOError('cwd lookup failed')
cookie_path = stem.util.system.expand_path(cookie_path, tor_cwd)
except IOError as exc:
resolver_labels = {
stem.util.system.pid_by_name: ' by name',
stem.util.system.pid_by_port: ' by port',
stem.util.system.pid_by_open_file: ' by socket file',
}
pid_resolver_label = resolver_labels.get(pid_resolver, '')
log.debug('unable to expand relative tor cookie path%s: %s' % (pid_resolver_label, exc))
protocolinfo_response.cookie_path = cookie_path
开发者ID:sammyshj,项目名称:stem,代码行数:32,代码来源:connection.py
示例2: get_bsd_jail_id
def get_bsd_jail_id(pid):
"""
Gets the jail id for a process. These seem to only exist for FreeBSD (this
style for jails does not exist on Linux, OSX, or OpenBSD).
:param int pid: process id of the jail id to be queried
:returns: **int** for the jail id, zero if this can't be determined
"""
# Output when called from a FreeBSD jail or when Tor isn't jailed:
# JID
# 0
#
# Otherwise it's something like:
# JID
# 1
ps_output = call(GET_BSD_JAIL_ID_PS % pid)
if ps_output and len(ps_output) == 2 and len(ps_output[1].split()) == 1:
jid = ps_output[1].strip()
if jid.isdigit():
return int(jid)
os_name = platform.system()
if os_name == "FreeBSD":
log.warn("Unable to get the jail id for process %s." % pid)
else:
log.debug("get_bsd_jail_id(%s): jail ids do not exist on %s" % (pid, os_name))
return 0
开发者ID:ankitmodi,项目名称:Projects,代码行数:33,代码来源:system.py
示例3: _download_descriptors
def _download_descriptors(self, retries):
try:
use_authority = retries == 0 and self.fall_back_to_authority
self.download_url = self._pick_url(use_authority)
self.start_time = time.time()
response = urllib2.urlopen(self.download_url, timeout = self.timeout).read()
if self.download_url.endswith('.z'):
response = zlib.decompress(response)
self.content = response.strip()
self.runtime = time.time() - self.start_time
log.trace("Descriptors retrieved from '%s' in %0.2fs" % (self.download_url, self.runtime))
except:
exc = sys.exc_info()[1]
if retries > 0:
log.debug("Unable to download descriptors from '%s' (%i retries remaining): %s" % (self.download_url, retries, exc))
return self._download_descriptors(retries - 1)
else:
log.debug("Unable to download descriptors from '%s': %s" % (self.download_url, exc))
self.error = exc
finally:
self.is_done = True
开发者ID:santatic,项目名称:facebook-registry-python,代码行数:26,代码来源:remote.py
示例4: load
def load(self, path = None):
"""
Reads in the contents of the given path, adding its configuration values
to our current contents.
:param str path: file path to be loaded, this uses the last loaded path if
not provided
:raises:
* **IOError** if we fail to read the file (it doesn't exist, insufficient
permissions, etc)
* **ValueError** if no path was provided and we've never been provided one
"""
if path:
self._path = path
elif not self._path:
raise ValueError("Unable to load configuration: no path provided")
with open(self._path, "r") as config_file:
read_contents = config_file.readlines()
with self._contents_lock:
self._raw_contents = read_contents
remainder = list(self._raw_contents)
while remainder:
line = remainder.pop(0)
# strips any commenting or excess whitespace
comment_start = line.find("#")
if comment_start != -1:
line = line[:comment_start]
line = line.strip()
# parse the key/value pair
if line:
try:
key, value = line.split(" ", 1)
value = value.strip()
except ValueError:
log.debug("Config entry '%s' is expected to be of the format 'Key Value', defaulting to '%s' -> ''" % (line, line))
key, value = line, ""
if not value:
# this might be a multi-line entry, try processing it as such
multiline_buffer = []
while remainder and remainder[0].lstrip().startswith("|"):
content = remainder.pop(0).lstrip()[1:] # removes '\s+|' prefix
content = content.rstrip("\n") # trailing newline
multiline_buffer.append(content)
if multiline_buffer:
self.set(key, "\n".join(multiline_buffer), False)
continue
self.set(key, value, False)
开发者ID:arlolra,项目名称:stem,代码行数:60,代码来源:conf.py
示例5: get_str_csv
def get_str_csv(self, key, default = None, count = None, sub_key = None):
"""
Fetches the given key as a comma separated value.
:param str key: config setting to be fetched, last if multiple exists
:param object default: value provided if no such key exists or doesn't match the count
:param int count: if set then the default is returned when the number of elements doesn't match this value
:param str sub_key: handle the configuration entry as a dictionary and use this key within it
:returns: list with the stripped values
"""
if sub_key: conf_value = self.get(key, {}).get(sub_key)
else: conf_value = self.get_value(key)
if conf_value is None: return default
elif not conf_value.strip(): return [] # empty string
else:
conf_comp = [entry.strip() for entry in conf_value.split(",")]
# check if the count doesn't match
if count != None and len(conf_comp) != count:
msg = "Config entry '%s' is expected to be %i comma separated values" % (key, count)
if default != None and (isinstance(default, list) or isinstance(default, tuple)):
defaultStr = ", ".join([str(i) for i in default])
msg += ", defaulting to '%s'" % defaultStr
log.debug(msg)
return default
return conf_comp
开发者ID:jacthinman,项目名称:Tor-Stem,代码行数:31,代码来源:conf.py
示例6: call
def call(command, default = UNDEFINED, ignore_exit_status = False):
"""
Issues a command in a subprocess, blocking until completion and returning the
results. This is not actually ran in a shell so pipes and other shell syntax
are not permitted.
:param str,list command: command to be issued
:param object default: response if the query fails
:param bool ignore_exit_status: reports failure if our command's exit status
was non-zero
:returns: **list** with the lines of output from the command
:raises: **OSError** if this fails and no default was provided
"""
if isinstance(command, str):
command_list = command.split(' ')
else:
command_list = command
try:
is_shell_command = command_list[0] in SHELL_COMMANDS
start_time = time.time()
process = subprocess.Popen(command_list, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = is_shell_command)
stdout, stderr = process.communicate()
stdout, stderr = stdout.strip(), stderr.strip()
runtime = time.time() - start_time
log.debug('System call: %s (runtime: %0.2f)' % (command, runtime))
trace_prefix = 'Received from system (%s)' % command
if stdout and stderr:
log.trace(trace_prefix + ', stdout:\n%s\nstderr:\n%s' % (stdout, stderr))
elif stdout:
log.trace(trace_prefix + ', stdout:\n%s' % stdout)
elif stderr:
log.trace(trace_prefix + ', stderr:\n%s' % stderr)
exit_code = process.poll()
if not ignore_exit_status and exit_code != 0:
raise OSError('%s returned exit status %i' % (command, exit_code))
if stdout:
return stdout.decode('utf-8', 'replace').splitlines()
else:
return []
except OSError as exc:
log.debug('System call (failed): %s (error: %s)' % (command, exc))
if default != UNDEFINED:
return default
else:
raise exc
开发者ID:5up3rc,项目名称:spiderfoot,代码行数:57,代码来源:system.py
示例7: _log_failure
def _log_failure(parameter, exc):
"""
Logs a message indicating that the proc query failed.
:param str parameter: description of the proc attribute being fetch
:param Exception exc: exception that we're raising
"""
log.debug("proc call failed (%s): %s" % (parameter, exc))
开发者ID:DanielMason,项目名称:torshare,代码行数:9,代码来源:proc.py
示例8: __init__
def __init__(self, use_mirrors = False, **default_args):
self._default_args = default_args
self._endpoints = DIRECTORY_AUTHORITIES.values()
if use_mirrors:
try:
start_time = time.time()
self.use_directory_mirrors()
log.debug("Retrieved directory mirrors (took %0.2fs)" % (time.time() - start_time))
except Exception as exc:
log.debug("Unable to retrieve directory mirrors: %s" % exc)
开发者ID:arlolra,项目名称:stem,代码行数:11,代码来源:remote.py
示例9: _log_runtime
def _log_runtime(parameter, proc_location, start_time):
"""
Logs a message indicating a successful proc query.
:param str parameter: description of the proc attribute being fetch
:param str proc_location: proc files we were querying
:param int start_time: unix time for when this query was started
"""
runtime = time.time() - start_time
log.debug("proc call (%s): %s (runtime: %0.4f)" % (parameter, proc_location, runtime))
开发者ID:DanielMason,项目名称:torshare,代码行数:11,代码来源:proc.py
示例10: __init__
def __init__(self, use_mirrors = False, **default_args):
self._default_args = default_args
authorities = filter(HAS_V3IDENT, get_authorities().values())
self._endpoints = [(auth.address, auth.dir_port) for auth in authorities]
if use_mirrors:
try:
start_time = time.time()
self.use_directory_mirrors()
log.debug('Retrieved directory mirrors (took %0.2fs)' % (time.time() - start_time))
except Exception as exc:
log.debug('Unable to retrieve directory mirrors: %s' % exc)
开发者ID:santatic,项目名称:facebook-registry-python,代码行数:13,代码来源:remote.py
示例11: get_int_csv
def get_int_csv(self, key, default=None, count=None, min_value=None, max_value=None, sub_key=None):
"""
Fetches the given comma separated value, returning the default if the
values aren't integers or don't follow the given constraints.
:param str key: config setting to be fetched, last if multiple exists
:param object default: value provided if no such key exists, doesn't match
the count, values aren't all integers, or doesn't match the bounds
:param int count: checks that the number of values matches this if set
:param int min_value: checks that all values are over this if set
:param int max_value: checks that all values are under this if set
:param str sub_key: handle the configuration entry as a dictionary and use
this key within it
:returns: **list** with the stripped values
"""
conf_comp = self.get_str_csv(key, default, count, sub_key)
if conf_comp == default:
return default
# validates the input, setting the error_msg if there's a problem
error_msg = None
base_error_msg = "Config entry '%s' is expected to %%s" % key
# includes our default value in the message
if default != None and (isinstance(default, list) or isinstance(default, tuple)):
default_str = ", ".join([str(i) for i in default])
base_error_msg += ", defaulting to '%s'" % default_str
for val in conf_comp:
if not val.isdigit():
error_msg = base_error_msg % "only have integer values"
break
else:
if min_value != None and int(val) < min_value:
error_msg = base_error_msg % "only have values over %i" % min_value
break
elif max_value != None and int(val) > max_value:
error_msg = base_error_msg % "only have values less than %i" % max_value
break
if error_msg:
log.debug(error_msg)
return default
else:
return [int(val) for val in conf_comp]
开发者ID:eoinof,项目名称:stem,代码行数:47,代码来源:conf.py
示例12: __init__
def __init__(self):
nyx.panel.Panel.__init__(self)
self._contents = []
self._scroller = nyx.curses.CursorScroller()
self._sort_order = CONFIG['features.config.order']
self._show_all = False # show all options, or just the important ones
cached_manual_path = os.path.join(DATA_DIR, 'manual')
if os.path.exists(cached_manual_path):
manual = stem.manual.Manual.from_cache(cached_manual_path)
else:
try:
manual = stem.manual.Manual.from_man()
try:
manual.save(cached_manual_path)
except IOError as exc:
log.debug("Unable to cache manual information to '%s'. This is fine, but means starting Nyx takes a little longer than usual: " % (cached_manual_path, exc))
except IOError as exc:
log.debug("Unable to use 'man tor' to get information about config options (%s), using bundled information instead" % exc)
manual = stem.manual.Manual.from_cache()
try:
for line in tor_controller().get_info('config/names').splitlines():
# Lines of the form "<option> <type>[ <documentation>]". Documentation
# was apparently only in old tor versions like 0.2.1.25.
if ' ' not in line:
continue
line_comp = line.split()
name, value_type = line_comp[0], line_comp[1]
# skips private and virtual entries if not configured to show them
if name.startswith('__') and not CONFIG['features.config.state.showPrivateOptions']:
continue
elif value_type == 'Virtual' and not CONFIG['features.config.state.showVirtualOptions']:
continue
self._contents.append(ConfigEntry(name, value_type, manual))
self._contents = sorted(self._contents, key = lambda entry: [entry.sort_value(field) for field in self._sort_order])
except stem.ControllerError as exc:
log.warn('Unable to determine the configuration options tor supports: %s' % exc)
开发者ID:sammyshj,项目名称:nyx,代码行数:47,代码来源:config.py
示例13: _reset_subwindow
def _reset_subwindow(self):
"""
Create a new subwindow instance for the panel if:
- Panel currently doesn't have a subwindow (was uninitialized or
invalidated).
- There's room for the panel to grow vertically (curses automatically
lets subwindows regrow horizontally, but not vertically).
- The subwindow has been displaced. This is a curses display bug that
manifests if the terminal's shrank then re-expanded. Displaced
subwindows are never restored to their proper position, resulting in
graphical glitches if we draw to them.
- The preferred size is smaller than the actual size (should shrink).
This returns True if a new subwindow instance was created, False otherwise.
"""
new_height, new_width = self.get_preferred_size()
if new_height == 0:
return False # subwindow would be outside its parent
# determines if a new subwindow should be recreated
recreate = self.win is None
if self.win:
subwin_max_y, subwin_max_x = self.win.getmaxyx()
recreate |= subwin_max_y < new_height # check for vertical growth
recreate |= self.top > self.win.getparyx()[0] # check for displacement
recreate |= subwin_max_x > new_width or subwin_max_y > new_height # shrinking
# I'm not sure if recreating subwindows is some sort of memory leak but the
# Python curses bindings seem to lack all of the following:
# - subwindow deletion (to tell curses to free the memory)
# - subwindow moving/resizing (to restore the displaced windows)
# so this is the only option (besides removing subwindows entirely which
# would mean far more complicated code and no more selective refreshing)
if recreate:
self.win = self.parent.subwin(new_height, new_width, self.top, self.left)
# note: doing this log before setting win produces an infinite loop
log.debug("recreating panel '%s' with the dimensions of %i/%i" % (self.get_name(), new_height, new_width))
return recreate
开发者ID:isislovecruft,项目名称:arm,代码行数:45,代码来源:panel.py
示例14: call
def call(command, default = UNDEFINED):
"""
Issues a command in a subprocess, blocking until completion and returning the
results. This is not actually ran in a shell so pipes and other shell syntax
are not permitted.
:param str command: command to be issued
:param object default: response if the query fails
:returns: **list** with the lines of output from the command
:raises: **OSError** if this fails and no default was provided
"""
try:
is_shell_command = command.split(" ")[0] in SHELL_COMMANDS
start_time = time.time()
stdout, stderr = subprocess.Popen(command.split(), stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = is_shell_command).communicate()
stdout, stderr = stdout.strip(), stderr.strip()
runtime = time.time() - start_time
log.debug("System call: %s (runtime: %0.2f)" % (command, runtime))
trace_prefix = "Received from system (%s)" % command
if stdout and stderr:
log.trace(trace_prefix + ", stdout:\n%s\nstderr:\n%s" % (stdout, stderr))
elif stdout:
log.trace(trace_prefix + ", stdout:\n%s" % stdout)
elif stderr:
log.trace(trace_prefix + ", stderr:\n%s" % stderr)
if stdout:
return stdout.decode("utf-8", "replace").splitlines()
else:
return []
except OSError, exc:
log.debug("System call (failed): %s (error: %s)" % (command, exc))
if default != UNDEFINED:
return default
else:
raise exc
开发者ID:ankitmodi,项目名称:Projects,代码行数:43,代码来源:system.py
示例15: call
def call(command, suppress_exc = True):
"""
Issues a command in a subprocess, blocking until completion and returning the
results. This is not actually ran in a shell so pipes and other shell syntax
are not permitted.
:param str command: command to be issued
:param bool suppress_exc: if **True** then **None** is returned on failure,
otherwise this raises the exception
:returns: **list** with the lines of output from the command, **None** in
case of failure if suppress_exc is **True**
:raises: **OSError** if this fails and suppress_exc is **False**
"""
try:
start_time = time.time()
stdout, stderr = subprocess.Popen(command.split(), stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
stdout, stderr = stdout.strip(), stderr.strip()
runtime = time.time() - start_time
log.debug("System call: %s (runtime: %0.2f)" % (command, runtime))
trace_prefix = "Received from system (%s)" % command
if stdout and stderr:
log.trace(trace_prefix + ", stdout:\n%s\nstderr:\n%s" % (stdout, stderr))
elif stdout:
log.trace(trace_prefix + ", stdout:\n%s" % stdout)
elif stderr:
log.trace(trace_prefix + ", stderr:\n%s" % stderr)
if stdout: return stdout.splitlines()
else: return []
except OSError, exc:
log.debug("System call (failed): %s (error: %s)" % (command, exc))
if suppress_exc: return None
else: raise exc
开发者ID:eoinof,项目名称:stem,代码行数:39,代码来源:system.py
示例16: len
# remove authentication methods that are either unknown or for which we don't
# have an input
if AuthMethod.UNKNOWN in auth_methods:
auth_methods.remove(AuthMethod.UNKNOWN)
unknown_methods = protocolinfo_response.unknown_auth_methods
plural_label = "s" if len(unknown_methods) > 1 else ""
methods_label = ", ".join(unknown_methods)
# we... er, can't do anything with only unrecognized auth types
if not auth_methods:
exc_msg = "unrecognized authentication method%s (%s)" % (plural_label, methods_label)
auth_exceptions.append(UnrecognizedAuthMethods(exc_msg, unknown_methods))
else:
log.debug("Authenticating to a socket with unrecognized auth method%s, ignoring them: %s" % (plural_label, methods_label))
if protocolinfo_response.cookie_path is None:
for cookie_auth_method in (AuthMethod.COOKIE, AuthMethod.SAFECOOKIE):
if cookie_auth_method in auth_methods:
auth_methods.remove(cookie_auth_method)
exc_msg = "our PROTOCOLINFO response did not have the location of our authentication cookie"
auth_exceptions.append(NoAuthCookie(exc_msg, cookie_auth_method == AuthMethod.SAFECOOKIE))
if AuthMethod.PASSWORD in auth_methods and password is None:
auth_methods.remove(AuthMethod.PASSWORD)
auth_exceptions.append(MissingPassword("no passphrase provided"))
# iterating over AuthMethods so we can try them in this order
for auth_type in (AuthMethod.NONE, AuthMethod.PASSWORD, AuthMethod.SAFECOOKIE, AuthMethod.COOKIE):
开发者ID:gsathya,项目名称:stem,代码行数:30,代码来源:connection.py
示例17: get
def get(self, key, default = None):
"""
Fetches the given configuration, using the key and default value to
determine the type it should be. Recognized inferences are:
* **default is a boolean => boolean**
* values are case insensitive
* provides the default if the value isn't "true" or "false"
* **default is an integer => int**
* provides the default if the value can't be converted to an int
* **default is a float => float**
* provides the default if the value can't be converted to a float
* **default is a list => list**
* string contents for all configuration values with this key
* **default is a tuple => tuple**
* string contents for all configuration values with this key
* **default is a dictionary => dict**
* values without "=>" in them are ignored
* values are split into key/value pairs on "=>" with extra whitespace
stripped
:param str key: config setting to be fetched
:param default object: value provided if no such key exists or fails to be converted
:returns: given configuration value with its type inferred with the above rules
"""
is_multivalue = isinstance(default, (list, tuple, dict))
val = self.get_value(key, default, is_multivalue)
if val == default:
return val # don't try to infer undefined values
if isinstance(default, bool):
if val.lower() == "true":
val = True
elif val.lower() == "false":
val = False
else:
log.debug("Config entry '%s' is expected to be a boolean, defaulting to '%s'" % (key, str(default)))
val = default
elif isinstance(default, int):
try:
val = int(val)
except ValueError:
log.debug("Config entry '%s' is expected to be an integer, defaulting to '%i'" % (key, default))
val = default
elif isinstance(default, float):
try:
val = float(val)
except ValueError:
log.debug("Config entry '%s' is expected to be a float, defaulting to '%f'" % (key, default))
val = default
elif isinstance(default, list):
pass # nothing special to do (already a list)
elif isinstance(default, tuple):
val = tuple(val)
elif isinstance(default, dict):
valMap = {}
for entry in val:
if "=>" in entry:
entryKey, entryVal = entry.split("=>", 1)
valMap[entryKey.strip()] = entryVal.strip()
else:
log.debug("Ignoring invalid %s config entry (expected a mapping, but \"%s\" was missing \"=>\")" % (key, entry))
val = valMap
return val
开发者ID:arlolra,项目名称:stem,代码行数:79,代码来源:conf.py
示例18: call
def call(command, default = UNDEFINED, ignore_exit_status = False, timeout = None, cwd = None, env = None):
"""
call(command, default = UNDEFINED, ignore_exit_status = False)
Issues a command in a subprocess, blocking until completion and returning the
results. This is not actually ran in a shell so pipes and other shell syntax
are not permitted.
.. versionchanged:: 1.5.0
Providing additional information upon failure by raising a CallError. This
is a subclass of OSError, providing backward compatibility.
.. versionchanged:: 1.5.0
Added env argument.
.. versionchanged:: 1.6.0
Added timeout and cwd arguments.
:param str,list command: command to be issued
:param object default: response if the query fails
:param bool ignore_exit_status: reports failure if our command's exit status
was non-zero
:param float timeout: maximum seconds to wait, blocks indefinitely if
**None**
:param dict env: environment variables
:returns: **list** with the lines of output from the command
:raises:
* **CallError** if this fails and no default was provided
* **CallTimeoutError** if the timeout is reached without a default
"""
global SYSTEM_CALL_TIME
if isinstance(command, str):
command_list = command.split(' ')
else:
command_list = list(map(str, command))
exit_status, runtime, stdout, stderr = None, None, None, None
start_time = time.time()
try:
is_shell_command = command_list[0] in SHELL_COMMANDS
process = subprocess.Popen(command_list, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = is_shell_command, cwd = cwd, env = env)
if timeout:
while process.poll() is None:
if time.time() - start_time > timeout:
raise CallTimeoutError("Process didn't finish after %0.1f seconds" % timeout, ' '.join(command_list), None, timeout, '', '', timeout)
time.sleep(0.001)
stdout, stderr = process.communicate()
stdout, stderr = stdout.strip(), stderr.strip()
runtime = time.time() - start_time
log.debug('System call: %s (runtime: %0.2f)' % (command, runtime))
trace_prefix = 'Received from system (%s)' % command
if stdout and stderr:
log.trace(trace_prefix + ', stdout:\n%s\nstderr:\n%s' % (stdout, stderr))
elif stdout:
log.trace(trace_prefix + ', stdout:\n%s' % stdout)
elif stderr:
log.trace(trace_prefix + ', stderr:\n%s' % stderr)
exit_status = process.poll()
if not ignore_exit_status and exit_status != 0:
raise OSError('%s returned exit status %i' % (command, exit_status))
if stdout:
return stdout.decode('utf-8', 'replace').splitlines()
else:
return []
except CallTimeoutError as exc:
log.debug('System call (timeout): %s (after %0.4fs)' % (command, timeout))
if default != UNDEFINED:
return default
else:
raise
except OSError as exc:
log.debug('System call (failed): %s (error: %s)' % (command, exc))
if default != UNDEFINED:
return default
else:
raise CallError(str(exc), ' '.join(command_list), exit_status, runtime, stdout, stderr)
finally:
with SYSTEM_CALL_TIME_LOCK:
SYSTEM_CALL_TIME += time.time() - start_time
开发者ID:patrickod,项目名称:stem,代码行数:95,代码来源:system.py
示例19: get_info
def get_info(self, params, default = UNDEFINED):
"""
Queries the control socket for the given GETINFO option. If provided a
default then that's returned if the GETINFO option is undefined or the
call fails for any reason (error response, control port closed, initiated,
etc).
:param str,list param: GETINFO option or options to be queried
:param object default: response if the query fails
:returns:
Response depends upon how we were called as follows...
* **str** with the response if our param was a **str**
* **dict** with the 'param => response' mapping if our param was a **list**
* default if one was provided and our call failed
:raises:
* :class:`stem.socket.ControllerError` if the call fails and we weren't
provided a default response
* :class:`stem.socket.InvalidArguments` if the 'param' requested was
invalid
"""
start_time = time.time()
reply = {}
if isinstance(params, str):
is_multiple = False
params = set([params])
else:
if not params: return {}
is_multiple = True
params = set(params)
# check for cached results
for param in list(params):
cache_key = "getinfo.%s" % param.lower()
if cache_key in self._request_cache:
reply[param] = self._request_cache[cache_key]
params.remove(param)
elif param.startswith('ip-to-country/') and self.is_geoip_unavailable():
# the geoip database aleady looks to be unavailable - abort the request
raise stem.socket.ProtocolError("Tor geoip database is unavailable")
# if everything was cached then short circuit making the query
if not params:
log.debug("GETINFO %s (cache fetch)" % " ".join(reply.keys()))
if is_multiple: return reply
else: return reply.values()[0]
try:
response = self.msg("GETINFO %s" % " ".join(params))
stem.response.convert("GETINFO", response)
response.assert_matches(params)
reply.update(response.entries)
if self.is_caching_enabled():
for key, value in response.entries.items():
key = key.lower() # make case insensitive
if key in CACHEABLE_GETINFO_PARAMS:
self._request_cache["getinfo.%s" % key] = value
elif key.startswith('ip-to-country/'):
# both cache-able and means that we should reset the geoip failure count
self._request_cache["getinfo.%s" % key] = value
self._geoip_failure_count = -1
log.debug("GETINFO %s (runtime: %0.4f)" % (" ".join(params), time.time() - start_time))
if is_multiple:
return reply
else:
return reply.values()[0]
except stem.socket.ControllerError, exc:
# bump geoip failure count if...
# * we're caching results
# * this was soley a geoip lookup
# * we've never had a successful geoip lookup (failure count isn't -1)
is_geoip_request = len(params) == 1 and list(params)[0].startswith('ip-to-country/')
if is_geoip_request and self.is_caching_enabled() and self._geoip_failure_count != -1:
self._geoip_failure_count += 1
log.debug("GETINFO %s (failed: %s)" % (" ".join(params), exc))
if default == UNDEFINED: raise exc
else: return default
开发者ID:eoinof,项目名称:stem,代码行数:91,代码来源:control.py
示例20: get_cwd
def get_cwd(pid):
"""
Provides the working directory of the given process.
:param int pid: process id of the process to be queried
:returns: **str** with the absolute path for the process' present working
directory, **None** if it can't be determined
"""
# try fetching via the proc contents if it's available
if stem.util.proc.is_available():
try:
return stem.util.proc.get_cwd(pid)
except IOError:
pass
# Fall back to a pwdx query. This isn't available on BSD.
logging_prefix = "get_cwd(%s):" % pid
if is_available("pwdx"):
# pwdx results are of the form:
# 3799: /home/atagar
# 5839: No such process
results = call(GET_CWD_PWDX % pid)
if not results:
log.debug("%s pwdx didn't return any results" % logging_prefix)
elif results[0].endswith("No such process"):
log.debug("%s pwdx processes reported for this pid" % logging_prefix)
elif len(results) != 1 or results[0].count(" ") != 1 or not results[0].startswith("%s: " % pid):
log.debug("%s we got unexpected output from pwdx: %s" % (logging_prefix, results))
else:
return results[0].split(" ", 1)[1].strip()
# Use lsof as the final fallback. This is available on both Linux and is the
# only lookup method here that works for BSD...
# https://trac.torproject.org/projects/tor/ticket/4236
#
# flags:
# a - presents the intersection of the following arguments
# p - limits results to this pid
# d cwd - limits results to just the cwd rather than all open files
# Fn - short listing in a single column, with just the pid and cwd
#
# example output:
# ~$ lsof -a -p 75717 -d cwd -Fn
# p75717
# n/Users/atagar/tor/src/or
if is_available("lsof"):
results = call(GET_CWD_LSOF % pid)
if results and len(results) == 2 and results[1].startswith("n/"):
lsof_result = results[1][1:].strip()
# If we lack read permissions for the cwd then it returns...
# p2683
# n/proc/2683/cwd (readlink: Permission denied)
if not " " in lsof_result:
return lsof_result
else:
log.debug("%s we got unexpected output from lsof: %s" % (logging_prefix, results))
return None # all queries failed
开发者ID:ankitmodi,项目名称:Projects,代码行数:66,代码来源:system.py
注:本文中的stem.util.log.debug函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论