desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Gets the ``tzinfo`` of the :class:`Arrow <arrow.arrow.Arrow>` object.'
@property def tzinfo(self):
return self._datetime.tzinfo
'Sets the ``tzinfo`` of the :class:`Arrow <arrow.arrow.Arrow>` object.'
@tzinfo.setter def tzinfo(self, tzinfo):
self._datetime = self._datetime.replace(tzinfo=tzinfo)
'Returns a datetime representation of the :class:`Arrow <arrow.arrow.Arrow>` object.'
@property def datetime(self):
return self._datetime
'Returns a naive datetime representation of the :class:`Arrow <arrow.arrow.Arrow>` object.'
@property def naive(self):
return self._datetime.replace(tzinfo=None)
'Returns a timestamp representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in UTC time.'
@property def timestamp(self):
return calendar.timegm(self._datetime.utctimetuple())
'Returns a floating-point representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in UTC time.'
@property def float_timestamp(self):
return (self.timestamp + (float(self.microsecond) / 1000000))
'Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, cloned from the current one. Usage: >>> arw = arrow.utcnow() >>> cloned = arw.clone()'
def clone(self):
return self.fromdatetime(self._datetime)
'Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated according to inputs. Use property names to set their value absolutely:: >>> import arrow >>> arw = arrow.utcnow() >>> arw <Arrow [2013-05-11T22:27:34.787885+00:00]> >>> arw.replace(year=2014, month=6) <Arrow [2014-06-11T22:27:34.787885+00:...
def replace(self, **kwargs):
absolute_kwargs = {} relative_kwargs = {} for (key, value) in kwargs.items(): if (key in self._ATTRS): absolute_kwargs[key] = value elif ((key in self._ATTRS_PLURAL) or (key in ['weeks', 'quarters'])): warnings.warn('replace() with plural property to sh...
'Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated according to inputs. Use pluralized property names to shift their current value relatively: >>> import arrow >>> arw = arrow.utcnow() >>> arw <Arrow [2013-05-11T22:27:34.787885+00:00]> >>> arw.shift(years=1, months=-1) <Arrow [2014-04-11T2...
def shift(self, **kwargs):
relative_kwargs = {} for (key, value) in kwargs.items(): if ((key in self._ATTRS_PLURAL) or (key in ['weeks', 'quarters', 'weekday'])): relative_kwargs[key] = value else: raise AttributeError() relative_kwargs.setdefault('months', 0) relative_kwargs['months'] += (...
'Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, converted to the target timezone. :param tz: A :ref:`timezone expression <tz-expr>`. Usage:: >>> utc = arrow.utcnow() >>> utc <Arrow [2013-05-09T03:49:12.311072+00:00]> >>> utc.to(\'US/Pacific\') <Arrow [2013-05-08T20:49:12.311072-07:00]> >>> utc.to(tz.tzlocal()...
def to(self, tz):
if (not isinstance(tz, tzinfo)): tz = parser.TzinfoParser.parse(tz) dt = self._datetime.astimezone(tz) return self.__class__(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
'Returns two new :class:`Arrow <arrow.arrow.Arrow>` objects, representing the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). :param count: (optional) the number of frames to span. Supported frame valu...
def span(self, frame, count=1):
(frame_absolute, frame_relative, relative_steps) = self._get_frames(frame) if (frame_absolute == 'week'): attr = 'day' elif (frame_absolute == 'quarter'): attr = 'month' else: attr = frame_absolute index = self._ATTRS.index(attr) frames = self._ATTRS[:(index + 1)] val...
'Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, representing the "floor" of the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe. Equivalent to the first element in the 2-tuple returned by :func:`span <arrow.arrow.Arrow.span>`. :param frame: the timeframe. Can be any ``datetime`...
def floor(self, frame):
return self.span(frame)[0]
'Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, representing the "ceiling" of the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe. Equivalent to the second element in the 2-tuple returned by :func:`span <arrow.arrow.Arrow.span>`. :param frame: the timeframe. Can be any ``dateti...
def ceil(self, frame):
return self.span(frame)[1]
'Returns a string representation of the :class:`Arrow <arrow.arrow.Arrow>` object, formatted according to a format string. :param fmt: the format string. Usage:: >>> arrow.utcnow().format(\'YYYY-MM-DD HH:mm:ss ZZ\') \'2013-05-09 03:56:47 -00:00\' >>> arrow.utcnow().format(\'X\') \'1368071882\' >>> arrow.utcnow().format...
def format(self, fmt='YYYY-MM-DD HH:mm:ssZZ', locale='en_us'):
return formatter.DateTimeFormatter(locale).format(self._datetime, fmt)
'Returns a localized, humanized representation of a relative difference in time. :param other: (optional) an :class:`Arrow <arrow.arrow.Arrow>` or ``datetime`` object. Defaults to now in the current :class:`Arrow <arrow.arrow.Arrow>` object\'s timezone. :param locale: (optional) a ``str`` specifying a locale. Defaults...
def humanize(self, other=None, locale='en_us', only_distance=False, granularity='auto'):
locale = locales.get_locale(locale) if (other is None): utc = datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc()) dt = utc.astimezone(self._datetime.tzinfo) elif isinstance(other, Arrow): dt = other._datetime elif isinstance(other, datetime): if (other.tzinfo is None): ...
'Returns a ``date`` object with the same year, month and day.'
def date(self):
return self._datetime.date()
'Returns a ``time`` object with the same hour, minute, second, microsecond.'
def time(self):
return self._datetime.time()
'Returns a ``time`` object with the same hour, minute, second, microsecond and tzinfo.'
def timetz(self):
return self._datetime.timetz()
'Returns a ``datetime`` object, converted to the specified timezone. :param tz: a ``tzinfo`` object.'
def astimezone(self, tz):
return self._datetime.astimezone(tz)
'Returns a ``timedelta`` object representing the whole number of minutes difference from UTC time.'
def utcoffset(self):
return self._datetime.utcoffset()
'Returns the daylight savings time adjustment.'
def dst(self):
return self._datetime.dst()
'Returns a ``time.struct_time``, in the current timezone.'
def timetuple(self):
return self._datetime.timetuple()
'Returns a ``time.struct_time``, in UTC time.'
def utctimetuple(self):
return self._datetime.utctimetuple()
'Returns the proleptic Gregorian ordinal of the date.'
def toordinal(self):
return self._datetime.toordinal()
'Returns the day of the week as an integer (0-6).'
def weekday(self):
return self._datetime.weekday()
'Returns the ISO day of the week as an integer (1-7).'
def isoweekday(self):
return self._datetime.isoweekday()
'Returns a 3-tuple, (ISO year, ISO week number, ISO weekday).'
def isocalendar(self):
return self._datetime.isocalendar()
'Returns an ISO 8601 formatted representation of the date and time.'
def isoformat(self, sep='T'):
return self._datetime.isoformat(sep)
'Returns a ctime formatted representation of the date and time.'
def ctime(self):
return self._datetime.ctime()
'Formats in the style of ``datetime.strptime``. :param format: the format string.'
def strftime(self, format):
return self._datetime.strftime(format)
'Serializes for the ``for_json`` protocol of simplejson.'
def for_json(self):
return self.isoformat()
'returns the index of certain set of attributes (of a link) in the self.a list If the set of attributes is not found, returns None'
def previousIndex(self, attrs):
if (not has_key(attrs, 'href')): return None i = (-1) for a in self.a: i += 1 match = 0 if (has_key(a, 'href') and (a['href'] == attrs['href'])): if (has_key(a, 'title') or has_key(attrs, 'title')): if (has_key(a, 'title') and has_key(attrs, 'title...
'handles various text emphases'
def handle_emphasis(self, start, tag_style, parent_style):
tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) strikethrough = (('line-through' in tag_emphasis) and self.hide_strikethrough) bold = (('bold' in tag_emphasis) and (not ('bold' in parent_emphasis))) italic = (('italic' in tag_emphasis) and (not ('i...
'calculate the nesting count of google doc lists'
def google_nest_count(self, style):
nest_count = 0 if ('margin-left' in style): nest_count = (int(style['margin-left'][:(-2)]) / self.google_list_indent) return nest_count
'Wrap all paragraphs in the provided text.'
def optwrap(self, text):
if (not self.body_width): return text assert wrap, 'Requires Python 2.3.' result = '' newlines = 0 for para in text.split('\n'): if (len(para) > 0): if (not skipwrap(para)): result += '\n'.join(wrap(para, self.body_width)) if para.end...
'Retrieves multiple process info in one shot as a raw tuple.'
@memoize_when_activated def oneshot(self):
ret = cext.proc_oneshot_info(self.pid) assert (len(ret) == len(kinfo_proc_map)) return ret
'Return process current working directory.'
@wrap_exceptions def cwd(self):
if (OPENBSD and (self.pid == 0)): return None elif NETBSD: with wrap_exceptions_procfs(self): return os.readlink(('/proc/%s/cwd' % self.pid)) elif hasattr(cext, 'proc_open_files'): return (cext.proc_cwd(self.pid) or None) else: raise NotImplementedError(('supp...
'Accept an "ip:port" address as displayed in /proc/net/* and convert it into a human readable form, like: "0500000A:0016" -> ("10.0.0.5", 22) "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521) The IP address portion is a little or big endian four-byte hexadecimal number; that is, the least significa...
@staticmethod def decode_address(addr, family):
(ip, port) = addr.split(':') port = int(port, 16) if (not port): return () if PY3: ip = ip.encode('ascii') if (family == socket.AF_INET): if LITTLE_ENDIAN: ip = socket.inet_ntop(family, base64.b16decode(ip)[::(-1)]) else: ip = socket.inet_ntop(...
'Parse /proc/net/tcp* and /proc/net/udp* files.'
@staticmethod def process_inet(file, family, type_, inodes, filter_pid=None):
if (file.endswith('6') and (not os.path.exists(file))): return with open_text(file, buffering=BIGFILE_BUFFERING) as f: f.readline() for (lineno, line) in enumerate(f, 1): try: (_, laddr, raddr, status, _, _, _, _, _, inode) = line.split()[:10] exce...
'Parse /proc/net/unix files.'
@staticmethod def process_unix(file, family, inodes, filter_pid=None):
with open_text(file, buffering=BIGFILE_BUFFERING) as f: f.readline() for line in f: tokens = line.split() try: (_, _, _, _, type_, _, inode) = tokens[0:7] except ValueError: if (' ' not in line): continue ...
'Parse /proc/{pid}/stat file. Return a list of fields where process name is in position 0. Using "man proc" as a reference: where "man proc" refers to position N, always substract 2 (e.g starttime pos 22 in \'man proc\' == pos 20 in the list returned here). The return value is cached in case oneshot() ctx manager is in...
@memoize_when_activated def _parse_stat_file(self):
with open_binary(('%s/%s/stat' % (self._procfs_path, self.pid))) as f: data = f.read() rpar = data.rfind(')') name = data[(data.find('(') + 1):rpar] others = data[(rpar + 2):].split() return ([name] + others)
'Read /proc/{pid}/stat file and return its content. The return value is cached in case oneshot() ctx manager is in use.'
@memoize_when_activated def _read_status_file(self):
with open_binary(('%s/%s/status' % (self._procfs_path, self.pid))) as f: return f.read()
'What CPU the process is on.'
@wrap_exceptions def cpu_num(self):
return int(self._parse_stat_file()[37])
'Get UNIX sockets used by process by parsing \'pfiles\' output.'
def _get_unix_sockets(self, pid):
cmd = ('pfiles %s' % pid) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() if PY3: (stdout, stderr) = [x.decode(sys.stdout.encoding) for x in (stdout, stderr)] if (p.returncode != 0): if ('permission denied...
'The process PID.'
@property def pid(self):
return self._pid
'Utility context manager which considerably speeds up the retrieval of multiple process information at the same time. Internally different process info (e.g. name, ppid, uids, gids, ...) may be fetched by using the same routine, but only one information is returned and the others are discarded. When using this context ...
@contextlib.contextmanager def oneshot(self):
if self._oneshot_inctx: (yield) else: self._oneshot_inctx = True try: self.cpu_times.cache_activate() self.memory_info.cache_activate() self.ppid.cache_activate() if POSIX: self.uids.cache_activate() self._proc.o...
'Utility method returning process information as a hashable dictionary. If *attrs* is specified it must be a list of strings reflecting available Process class\' attribute names (e.g. [\'cpu_times\', \'name\']) else all public (read only) attributes are assumed. *ad_value* is the value which gets assigned in case Acces...
def as_dict(self, attrs=None, ad_value=None):
valid_names = _as_dict_attrnames if (attrs is not None): if (not isinstance(attrs, (list, tuple, set, frozenset))): raise TypeError(('invalid attrs type %s' % type(attrs))) attrs = set(attrs) invalid_names = (attrs - valid_names) if invalid_names: ...
'Return the parent process as a Process object pre-emptively checking whether PID has been reused. If no parent is known return None.'
def parent(self):
ppid = self.ppid() if (ppid is not None): ctime = self.create_time() try: parent = Process(ppid) if (parent.create_time() <= ctime): return parent except NoSuchProcess: pass
'Return whether this process is running. It also checks if PID has been reused by another process in which case return False.'
def is_running(self):
if self._gone: return False try: return (self == Process(self.pid)) except ZombieProcess: return True except NoSuchProcess: self._gone = True return False
'The process parent PID. On Windows the return value is cached after first call.'
@memoize_when_activated def ppid(self):
if POSIX: return self._proc.ppid() else: self._ppid = (self._ppid or self._proc.ppid()) return self._ppid
'The process name. The return value is cached after first call.'
def name(self):
if (WINDOWS and (self._name is not None)): return self._name name = self._proc.name() if (POSIX and (len(name) >= 15)): try: cmdline = self.cmdline() except AccessDenied: pass else: if cmdline: extended_name = os.path.basena...
'The process executable as an absolute path. May also be an empty string. The return value is cached after first call.'
def exe(self):
def guess_it(fallback): cmdline = self.cmdline() if (cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK')): exe = cmdline[0] if (os.path.isabs(exe) and os.path.isfile(exe) and os.access(exe, os.X_OK)): return exe if isinstance(fallback, AccessDeni...
'The command line this process has been called with.'
def cmdline(self):
return self._proc.cmdline()
'The process current status as a STATUS_* constant.'
def status(self):
try: return self._proc.status() except ZombieProcess: return STATUS_ZOMBIE
'The name of the user that owns the process. On UNIX this is calculated by using *real* process uid.'
def username(self):
if POSIX: if (pwd is None): raise ImportError('requires pwd module shipped with standard python') real_uid = self.uids().real try: return pwd.getpwuid(real_uid).pw_name except KeyError: return str(real_uid) else: retur...
'The process creation time as a floating point number expressed in seconds since the epoch, in UTC. The return value is cached after first call.'
def create_time(self):
if (self._create_time is None): self._create_time = self._proc.create_time() return self._create_time
'Process current working directory as an absolute path.'
def cwd(self):
return self._proc.cwd()
'Get or set process niceness (priority).'
def nice(self, value=None):
if (value is None): return self._proc.nice_get() else: if (not self.is_running()): raise NoSuchProcess(self.pid, self._name) self._proc.nice_set(value)
'Return the number of voluntary and involuntary context switches performed by this process.'
def num_ctx_switches(self):
return self._proc.num_ctx_switches()
'Return the number of threads used by this process.'
def num_threads(self):
return self._proc.num_threads()
'Return threads opened by process as a list of (id, user_time, system_time) namedtuples representing thread id and thread CPU times (user/system). On OpenBSD this method requires root access.'
def threads(self):
return self._proc.threads()
'Return the children of this process as a list of Process instances, pre-emptively checking whether PID has been reused. If *recursive* is True return all the parent descendants. Example (A == this process): A ─┐ ├─ B (child) ─┐ │ └─ X (grandchild) ─┐ │ ...
@_assert_pid_not_reused def children(self, recursive=False):
if hasattr(_psplatform, 'ppid_map'): ppid_map = _psplatform.ppid_map() else: ppid_map = None ret = [] if (not recursive): if (ppid_map is None): for p in process_iter(): try: if (p.ppid() == self.pid): if (se...
'Return a float representing the current process CPU utilization as a percentage. When *interval* is 0.0 or None (default) compares process times to system CPU times elapsed since last call, returning immediately (non-blocking). That means that the first time this is called it will return a meaningful 0.0 value. When *...
def cpu_percent(self, interval=None):
blocking = ((interval is not None) and (interval > 0.0)) if ((interval is not None) and (interval < 0)): raise ValueError(('interval is not positive (got %r)' % interval)) num_cpus = (cpu_count() or 1) def timer(): return (_timer() * num_cpus) if blocking: st1 ...
'Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds. This is similar to os.times() but per-process. On OSX and Windows children_user and children_system are always set to 0.'
@memoize_when_activated def cpu_times(self):
return self._proc.cpu_times()
'Return a namedtuple with variable fields depending on the platform, representing memory information about the process. The "portable" fields available on all plaforms are `rss` and `vms`. All numbers are expressed in bytes.'
@memoize_when_activated def memory_info(self):
return self._proc.memory_info()
'This method returns the same information as memory_info(), plus, on some platform (Linux, OSX, Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better representation of actual process memory usage. Namely USS is the memory which is unique to a process and which would be ...
def memory_full_info(self):
return self._proc.memory_full_info()
'Compare process memory to total physical system memory and calculate process memory utilization as a percentage. *memtype* argument is a string that dictates what type of process memory you want to compare against (defaults to "rss"). The list of available strings can be obtained like this: >>> psutil.Process().memory...
def memory_percent(self, memtype='rss'):
valid_types = list(_psplatform.pfullmem._fields) if hasattr(_psplatform, 'pfullmem'): valid_types.extend(list(_psplatform.pfullmem._fields)) if (memtype not in valid_types): raise ValueError(('invalid memtype %r; valid types are %r' % (memtype, tuple(valid_types)))) fun...
'Return files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number.'
def open_files(self):
return self._proc.open_files()
'Return socket connections opened by process as a list of (fd, family, type, laddr, raddr, status) namedtuples. The *kind* parameter filters for connections that match the following criteria: | Kind Value | Connections using | | inet | IPv4 and IPv6 ...
def connections(self, kind='inet'):
return self._proc.connections(kind)
'Send a signal *sig* to process pre-emptively checking whether PID has been reused (see signal module constants) . On Windows only SIGTERM is valid and is treated as an alias for kill().'
@_assert_pid_not_reused def send_signal(self, sig):
if POSIX: self._send_signal(sig) elif (sig == signal.SIGTERM): self._proc.kill() elif (sig in (getattr(signal, 'CTRL_C_EVENT', object()), getattr(signal, 'CTRL_BREAK_EVENT', object()))): self._proc.send_signal(sig) else: raise ValueError('only SIGTERM, CTRL_C_EVENT ...
'Suspend process execution with SIGSTOP pre-emptively checking whether PID has been reused. On Windows this has the effect ot suspending all process threads.'
@_assert_pid_not_reused def suspend(self):
if POSIX: self._send_signal(signal.SIGSTOP) else: self._proc.suspend()
'Resume process execution with SIGCONT pre-emptively checking whether PID has been reused. On Windows this has the effect of resuming all process threads.'
@_assert_pid_not_reused def resume(self):
if POSIX: self._send_signal(signal.SIGCONT) else: self._proc.resume()
'Terminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill().'
@_assert_pid_not_reused def terminate(self):
if POSIX: self._send_signal(signal.SIGTERM) else: self._proc.kill()
'Kill the current process with SIGKILL pre-emptively checking whether PID has been reused.'
@_assert_pid_not_reused def kill(self):
if POSIX: self._send_signal(signal.SIGKILL) else: self._proc.kill()
'Wait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. If the process is already terminated immediately return None instead of raising NoSuchProcess. If *timeout* (in seconds) is specified and process is still alive raise TimeoutExpired. To wait for multiple P...
def wait(self, timeout=None):
if ((timeout is not None) and (not (timeout >= 0))): raise ValueError('timeout must be a positive integer') return self._proc.wait(timeout)
'Test a callable.'
def execute(self, fun, *args, **kwargs):
def call_many_times(): for x in xrange(loops): self._call(fun, *args, **kwargs) del x gc.collect() tolerance = (kwargs.pop('tolerance_', None) or self.tolerance) loops = (kwargs.pop('loops_', None) or self.loops) retry_for = (kwargs.pop('retry_for_', None) or self.ret...
'Convenience function which tests a callable raising an exception.'
def execute_w_exc(self, exc, fun, *args, **kwargs):
def call(): self.assertRaises(exc, fun, *args, **kwargs) self.execute(call)
'Start thread and keep it running until an explicit stop() request. Polls for shutdown every \'timeout\' seconds.'
def start(self):
if self._running: raise ValueError('already started') threading.Thread.start(self) self._flag.wait()
'Stop thread execution and and waits until it is stopped.'
def stop(self):
if (not self._running): raise ValueError('already stopped') self._running = False self.join()
'Given a socket, makes sure it matches the one obtained via psutil. It assumes this process created one connection only (the one supposed to be checked).'
def check_socket(self, sock, conn=None):
if (conn is None): conn = self.get_conn_from_sock(sock) check_connection_ntuple(conn) if (conn.fd != (-1)): self.assertEqual(conn.fd, sock.fileno()) self.assertEqual(conn.family, sock.family) self.assertEqual(conn.type, sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)) laddr = ...
'Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections.'
def compare_procsys_connections(self, pid, proc_cons, kind='all'):
try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: if OSX: return else: raise sys_cons = [c[:(-1)] for c in sys_cons if (c.pid == pid)] sys_cons.sort() proc_cons.sort() self.assertEqual(proc_cons, sys_cons)
'Return True if /proc/meminfo provides swap metrics.'
@staticmethod def meminfo_has_swap_info():
with open('/proc/meminfo') as f: data = f.read() return (('SwapTotal:' in data) and ('SwapFree:' in data))
'In case the number of keys changed between calls (e.g. a disk disappears) this removes the entry from self.reminders.'
def _remove_dead_reminders(self, input_dict, name):
old_dict = self.cache[name] gone_keys = (set(old_dict.keys()) - set(input_dict.keys())) for gone_key in gone_keys: for remkey in self.reminder_keys[name][gone_key]: del self.reminders[name][remkey] del self.reminder_keys[name][gone_key]
'Cache dict and sum numbers which overflow and wrap. Return an updated copy of `input_dict`'
def run(self, input_dict, name):
if (name not in self.cache): self._add_dict(input_dict, name) return input_dict self._remove_dead_reminders(input_dict, name) old_dict = self.cache[name] new_dict = {} for key in input_dict.keys(): input_tuple = input_dict[key] try: old_tuple = old_dict[ke...
'Clear the internal cache, optionally only for function \'name\'.'
def cache_clear(self, name=None):
with self.lock: if (name is None): self.cache.clear() self.reminders.clear() self.reminder_keys.clear() else: self.cache.pop(name, None) self.reminders.pop(name, None) self.reminder_keys.pop(name, None)
'Return internal cache dicts as a tuple of 3 elements.'
def cache_info(self):
with self.lock: return (self.cache, self.reminders, self.reminder_keys)
'Ctx manager which translates bare OSError and WindowsError exceptions into NoSuchProcess and AccessDenied.'
@contextlib.contextmanager def _wrap_exceptions(self):
try: (yield) except WindowsError as err: if (err.errno in ACCESS_DENIED_ERRSET): raise AccessDenied(pid=None, name=self._name, msg=('service %r is not querable (not enough privileges)' % self._name)) elif ((err.errno in NO_SUCH_SERVICE_ERRSET) or (err.win...
'The service name. This string is how a service is referenced and can be passed to win_service_get() to get a new WindowsService instance.'
def name(self):
return self._name
'The service display name. The value is cached when this class is instantiated.'
def display_name(self):
return self._display_name
'The fully qualified path to the service binary/exe file as a string, including command line arguments.'
def binpath(self):
return self._query_config()['binpath']
'The name of the user that owns this service.'
def username(self):
return self._query_config()['username']
'A string which can either be "automatic", "manual" or "disabled".'
def start_type(self):
return self._query_config()['start_type']
'The process PID, if any, else None. This can be passed to Process class to control the service\'s process.'
def pid(self):
return self._query_status()['pid']
'Service status as a string.'
def status(self):
return self._query_status()['status']
'Service long description.'
def description(self):
return py2_strencode(cext.winservice_query_descr(self.name()))
'Utility method retrieving all the information above as a dictionary.'
def as_dict(self):
d = self._query_config() d.update(self._query_status()) d['name'] = self.name() d['display_name'] = self.display_name() d['description'] = self.description() return d
'Return multiple information about this process as a raw tuple.'
@memoize_when_activated def oneshot_info(self):
ret = cext.proc_info(self.pid) assert (len(ret) == len(pinfo_map)) return ret
'Return process name, which on Windows is always the final part of the executable.'
@wrap_exceptions def name(self):
if (self.pid == 0): return 'System Idle Process' elif (self.pid == 4): return 'System' else: try: return py2_strencode(os.path.basename(self.exe())) except AccessDenied: return py2_strencode(cext.proc_name(self.pid))
'using direct download for depth <= 2 using proxy with probability 0.3'
def use_proxy(self, request):
return True
'using direct download for depth <= 2 using proxy with probability 0.3'
def use_proxy(self, request):
return True