id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
176,195
from __future__ import absolute_import, division, print_function import sys from ._typing import TYPE_CHECKING The provided code snippet includes necessary dependencies for implementing the `with_metaclass` function. Write a Python function `def with_metaclass(meta, *bases)` to solve the following problem: Create a base class with a metaclass. Here is the function: def with_metaclass(meta, *bases): # type: (Type[Any], Tuple[Type[Any], ...]) -> Any """ Create a base class with a metaclass. """ # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): # type: ignore def __new__(cls, name, this_bases, d): # type: (Type[Any], str, Tuple[Any], Dict[Any, Any]) -> Any return meta(name, bases, d) return type.__new__(metaclass, "temporary_class", (), {})
Create a base class with a metaclass.
176,196
from __future__ import absolute_import, division, print_function import abc import functools import itertools import re from ._compat import string_types, with_metaclass from ._typing import TYPE_CHECKING from .utils import canonicalize_version from .version import Version, LegacyVersion, parse class Version(_BaseVersion): _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE) def __init__(self, version): # type: (str) -> None # Validate the version and parse it into pieces match = self._regex.search(version) if not match: raise InvalidVersion("Invalid version: '{0}'".format(version)) # Store the parsed out pieces of the version self._version = _Version( epoch=int(match.group("epoch")) if match.group("epoch") else 0, release=tuple(int(i) for i in match.group("release").split(".")), pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")), post=_parse_letter_version( match.group("post_l"), match.group("post_n1") or match.group("post_n2") ), dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")), local=_parse_local_version(match.group("local")), ) # Generate a key which will be used for sorting self._key = _cmpkey( self._version.epoch, self._version.release, self._version.pre, self._version.post, self._version.dev, self._version.local, ) def __repr__(self): # type: () -> str return "<Version({0})>".format(repr(str(self))) def __str__(self): # type: () -> str parts = [] # Epoch if self.epoch != 0: parts.append("{0}!".format(self.epoch)) # Release segment parts.append(".".join(str(x) for x in self.release)) # Pre-release if self.pre is not None: parts.append("".join(str(x) for x in self.pre)) # Post-release if self.post is not None: parts.append(".post{0}".format(self.post)) # Development release if self.dev is not None: parts.append(".dev{0}".format(self.dev)) # Local version segment if self.local is not None: parts.append("+{0}".format(self.local)) return "".join(parts) def epoch(self): # type: () -> int _epoch = self._version.epoch # type: int return _epoch def release(self): # type: () -> Tuple[int, ...] _release = self._version.release # type: Tuple[int, ...] return _release def pre(self): # type: () -> Optional[Tuple[str, int]] _pre = self._version.pre # type: Optional[Tuple[str, int]] return _pre def post(self): # type: () -> Optional[Tuple[str, int]] return self._version.post[1] if self._version.post else None def dev(self): # type: () -> Optional[Tuple[str, int]] return self._version.dev[1] if self._version.dev else None def local(self): # type: () -> Optional[str] if self._version.local: return ".".join(str(x) for x in self._version.local) else: return None def public(self): # type: () -> str return str(self).split("+", 1)[0] def base_version(self): # type: () -> str parts = [] # Epoch if self.epoch != 0: parts.append("{0}!".format(self.epoch)) # Release segment parts.append(".".join(str(x) for x in self.release)) return "".join(parts) def is_prerelease(self): # type: () -> bool return self.dev is not None or self.pre is not None def is_postrelease(self): # type: () -> bool return self.post is not None def is_devrelease(self): # type: () -> bool return self.dev is not None def major(self): # type: () -> int return self.release[0] if len(self.release) >= 1 else 0 def minor(self): # type: () -> int return self.release[1] if len(self.release) >= 2 else 0 def micro(self): # type: () -> int return self.release[2] if len(self.release) >= 3 else 0 def _require_version_compare( fn # type: (Callable[[Specifier, ParsedVersion, str], bool]) ): # type: (...) -> Callable[[Specifier, ParsedVersion, str], bool] @functools.wraps(fn) def wrapped(self, prospective, spec): # type: (Specifier, ParsedVersion, str) -> bool if not isinstance(prospective, Version): return False return fn(self, prospective, spec) return wrapped
null
176,197
from __future__ import absolute_import, division, print_function import abc import functools import itertools import re from ._compat import string_types, with_metaclass from ._typing import TYPE_CHECKING from .utils import canonicalize_version from .version import Version, LegacyVersion, parse _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") def _version_split(version): # type: (str) -> List[str] result = [] # type: List[str] for item in version.split("."): match = _prefix_regex.search(item) if match: result.extend(match.groups()) else: result.append(item) return result
null
176,198
from __future__ import absolute_import, division, print_function import abc import functools import itertools import re from ._compat import string_types, with_metaclass from ._typing import TYPE_CHECKING from .utils import canonicalize_version from .version import Version, LegacyVersion, parse def _pad_version(left, right): # type: (List[str], List[str]) -> Tuple[List[str], List[str]] left_split, right_split = [], [] # Get the release segment of our versions left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) # Get the rest of our versions left_split.append(left[len(left_split[0]) :]) right_split.append(right[len(right_split[0]) :]) # Insert our padding left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))
null
176,199
import inspect import typing as t from jupyter_core.utils import run_sync as _run_sync, ensure_async T = t.TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `run_sync` function. Write a Python function `def run_sync(coro: t.Callable[..., t.Union[T, t.Awaitable[T]]]) -> t.Callable[..., T]` to solve the following problem: Wraps coroutine in a function that blocks until it has executed. Parameters ---------- coro : coroutine-function The coroutine-function to be executed. Returns ------- result : Whatever the coroutine-function returns. Here is the function: def run_sync(coro: t.Callable[..., t.Union[T, t.Awaitable[T]]]) -> t.Callable[..., T]: """Wraps coroutine in a function that blocks until it has executed. Parameters ---------- coro : coroutine-function The coroutine-function to be executed. Returns ------- result : Whatever the coroutine-function returns. """ if not inspect.iscoroutinefunction(coro): return t.cast(t.Callable[..., T], coro) return _run_sync(coro)
Wraps coroutine in a function that blocks until it has executed. Parameters ---------- coro : coroutine-function The coroutine-function to be executed. Returns ------- result : Whatever the coroutine-function returns.
176,200
from __future__ import print_function import asyncio import base64 import errno from getpass import getpass from io import BytesIO import os from queue import Empty import signal import subprocess import sys from tempfile import TemporaryDirectory import time from warnings import warn from typing import Dict as DictType, Any as AnyType from zmq import ZMQError from IPython.core import page from traitlets import ( Bool, Integer, Float, Unicode, List, Dict, Enum, Instance, Any, ) from traitlets.config import SingletonConfigurable from .completer import ZMQCompleter from .zmqhistory import ZMQHistoryManager from . import __version__ from prompt_toolkit import __version__ as ptk_version from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.document import Document from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.filters import ( Condition, has_focus, has_selection, vi_insert_mode, emacs_insert_mode, is_done, ) from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.shortcuts.prompt import PromptSession from prompt_toolkit.shortcuts import print_formatted_text, CompleteStyle from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.layout.processors import ( ConditionalProcessor, HighlightMatchingBracketProcessor, ) from prompt_toolkit.styles import merge_styles from prompt_toolkit.styles.pygments import (style_from_pygments_cls, style_from_pygments_dict) from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.output import ColorDepth from prompt_toolkit.utils import suspend_to_background_supported from pygments.styles import get_style_by_name from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from pygments.token import Token from jupyter_console.utils import run_sync, ensure_async The provided code snippet includes necessary dependencies for implementing the `ask_yes_no` function. Write a Python function `def ask_yes_no(prompt, default=None, interrupt=None)` to solve the following problem: Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. Valid answers are: y/yes/n/no (match is not case sensitive). Here is the function: def ask_yes_no(prompt, default=None, interrupt=None): """Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. Valid answers are: y/yes/n/no (match is not case sensitive).""" answers = {'y': True, 'n': False, 'yes': True, 'no': False} ans = None while ans not in answers.keys(): try: ans = input(prompt + ' ').lower() if not ans: # response was an empty string ans = default except KeyboardInterrupt: if interrupt: ans = interrupt except EOFError: if default in answers.keys(): ans = default print() else: raise return answers[ans]
Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. Valid answers are: y/yes/n/no (match is not case sensitive).
176,201
from __future__ import print_function import asyncio import base64 import errno from getpass import getpass from io import BytesIO import os from queue import Empty import signal import subprocess import sys from tempfile import TemporaryDirectory import time from warnings import warn from typing import Dict as DictType, Any as AnyType from zmq import ZMQError from IPython.core import page from traitlets import ( Bool, Integer, Float, Unicode, List, Dict, Enum, Instance, Any, ) from traitlets.config import SingletonConfigurable from .completer import ZMQCompleter from .zmqhistory import ZMQHistoryManager from . import __version__ from prompt_toolkit import __version__ as ptk_version from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.document import Document from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.filters import ( Condition, has_focus, has_selection, vi_insert_mode, emacs_insert_mode, is_done, ) from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.shortcuts.prompt import PromptSession from prompt_toolkit.shortcuts import print_formatted_text, CompleteStyle from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.layout.processors import ( ConditionalProcessor, HighlightMatchingBracketProcessor, ) from prompt_toolkit.styles import merge_styles from prompt_toolkit.styles.pygments import (style_from_pygments_cls, style_from_pygments_dict) from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.output import ColorDepth from prompt_toolkit.utils import suspend_to_background_supported from pygments.styles import get_style_by_name from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from pygments.token import Token from jupyter_console.utils import run_sync, ensure_async The provided code snippet includes necessary dependencies for implementing the `async_input` function. Write a Python function `async def async_input(prompt, loop=None)` to solve the following problem: Simple async version of input using a the default executor Here is the function: async def async_input(prompt, loop=None): """Simple async version of input using a the default executor""" if loop is None: loop = asyncio.get_event_loop() raw = await loop.run_in_executor(None, input, prompt) return raw
Simple async version of input using a the default executor
176,202
from __future__ import print_function import asyncio import base64 import errno from getpass import getpass from io import BytesIO import os from queue import Empty import signal import subprocess import sys from tempfile import TemporaryDirectory import time from warnings import warn from typing import Dict as DictType, Any as AnyType from zmq import ZMQError from IPython.core import page from traitlets import ( Bool, Integer, Float, Unicode, List, Dict, Enum, Instance, Any, ) from traitlets.config import SingletonConfigurable from .completer import ZMQCompleter from .zmqhistory import ZMQHistoryManager from . import __version__ from prompt_toolkit import __version__ as ptk_version from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.document import Document from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.filters import ( Condition, has_focus, has_selection, vi_insert_mode, emacs_insert_mode, is_done, ) from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.shortcuts.prompt import PromptSession from prompt_toolkit.shortcuts import print_formatted_text, CompleteStyle from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.layout.processors import ( ConditionalProcessor, HighlightMatchingBracketProcessor, ) from prompt_toolkit.styles import merge_styles from prompt_toolkit.styles.pygments import (style_from_pygments_cls, style_from_pygments_dict) from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.output import ColorDepth from prompt_toolkit.utils import suspend_to_background_supported from pygments.styles import get_style_by_name from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from pygments.token import Token from jupyter_console.utils import run_sync, ensure_async def get_lexer_by_name(_alias, **options): """Get a lexer by an alias. Raises ClassNotFound if not found. """ if not _alias: raise ClassNotFound('no lexer for alias %r found' % _alias) # lookup builtin lexers for module_name, name, aliases, _, _ in LEXERS.values(): if _alias.lower() in aliases: if name not in _lexer_cache: _load_lexers(module_name) return _lexer_cache[name](**options) # continue with lexers from setuptools entrypoints for cls in find_plugin_lexers(): if _alias.lower() in cls.aliases: return cls(**options) raise ClassNotFound('no lexer for alias %r found' % _alias) class ClassNotFound(ValueError): """Raised if one of the lookup functions didn't find a matching class.""" IPython3Lexer = build_ipy_lexer(python3=True) IPythonLexer = build_ipy_lexer(python3=False) class TextLexer(Lexer): """ "Null" lexer, doesn't highlight anything. """ name = 'Text only' aliases = ['text'] filenames = ['*.txt'] mimetypes = ['text/plain'] priority = 0.01 def get_tokens_unprocessed(self, text): yield 0, Text, text def analyse_text(text): return TextLexer.priority def get_pygments_lexer(name): name = name.lower() if name == 'ipython2': from IPython.lib.lexers import IPythonLexer return IPythonLexer elif name == 'ipython3': from IPython.lib.lexers import IPython3Lexer return IPython3Lexer else: try: return get_lexer_by_name(name).__class__ except ClassNotFound: warn("No lexer found for language %r. Treating as plain text." % name) from pygments.lexers.special import TextLexer return TextLexer
null
176,203
import asyncio import asyncio.events as events import os import sys import threading from contextlib import contextmanager, suppress from heapq import heappop def _patch_asyncio(): """Patch asyncio module to use pure Python tasks and futures.""" def run(main, *, debug=False): try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) _patch_loop(loop) loop.set_debug(debug) task = asyncio.ensure_future(main) try: return loop.run_until_complete(task) finally: if not task.done(): task.cancel() with suppress(asyncio.CancelledError): loop.run_until_complete(task) def _get_event_loop(stacklevel=3): loop = events._get_running_loop() if loop is None: loop = events.get_event_loop_policy().get_event_loop() return loop # Use module level _current_tasks, all_tasks and patch run method. if hasattr(asyncio, '_nest_patched'): return if sys.version_info >= (3, 6, 0): asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \ asyncio.tasks._PyTask asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \ asyncio.futures._PyFuture if sys.version_info < (3, 7, 0): asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks asyncio.all_tasks = asyncio.tasks.Task.all_tasks if sys.version_info >= (3, 9, 0): events._get_event_loop = events.get_event_loop = \ asyncio.get_event_loop = _get_event_loop _get_event_loop asyncio.run = run asyncio._nest_patched = True def _patch_loop(loop): """Patch loop to make it reentrant.""" def run_forever(self): with manage_run(self), manage_asyncgens(self): while True: self._run_once() if self._stopping: break self._stopping = False def run_until_complete(self, future): with manage_run(self): f = asyncio.ensure_future(future, loop=self) if f is not future: f._log_destroy_pending = False while not f.done(): self._run_once() if self._stopping: break if not f.done(): raise RuntimeError( 'Event loop stopped before Future completed.') return f.result() def _run_once(self): """ Simplified re-implementation of asyncio's _run_once that runs handles as they become ready. """ ready = self._ready scheduled = self._scheduled while scheduled and scheduled[0]._cancelled: heappop(scheduled) timeout = ( 0 if ready or self._stopping else min(max( scheduled[0]._when - self.time(), 0), 86400) if scheduled else None) event_list = self._selector.select(timeout) self._process_events(event_list) end_time = self.time() + self._clock_resolution while scheduled and scheduled[0]._when < end_time: handle = heappop(scheduled) ready.append(handle) for _ in range(len(ready)): if not ready: break handle = ready.popleft() if not handle._cancelled: handle._run() handle = None def manage_run(self): """Set up the loop for running.""" self._check_closed() old_thread_id = self._thread_id old_running_loop = events._get_running_loop() try: self._thread_id = threading.get_ident() events._set_running_loop(self) self._num_runs_pending += 1 if self._is_proactorloop: if self._self_reading_future is None: self.call_soon(self._loop_self_reading) yield finally: self._thread_id = old_thread_id events._set_running_loop(old_running_loop) self._num_runs_pending -= 1 if self._is_proactorloop: if (self._num_runs_pending == 0 and self._self_reading_future is not None): ov = self._self_reading_future._ov self._self_reading_future.cancel() if ov is not None: self._proactor._unregister(ov) self._self_reading_future = None def manage_asyncgens(self): if not hasattr(sys, 'get_asyncgen_hooks'): # Python version is too old. return old_agen_hooks = sys.get_asyncgen_hooks() try: self._set_coroutine_origin_tracking(self._debug) if self._asyncgens is not None: sys.set_asyncgen_hooks( firstiter=self._asyncgen_firstiter_hook, finalizer=self._asyncgen_finalizer_hook) yield finally: self._set_coroutine_origin_tracking(False) if self._asyncgens is not None: sys.set_asyncgen_hooks(*old_agen_hooks) def _check_running(self): """Do not throw exception if loop is already running.""" pass if hasattr(loop, '_nest_patched'): return if not isinstance(loop, asyncio.BaseEventLoop): raise ValueError('Can\'t patch loop of type %s' % type(loop)) cls = loop.__class__ cls.run_forever = run_forever cls.run_until_complete = run_until_complete cls._run_once = _run_once cls._check_running = _check_running cls._check_runnung = _check_running # typo in Python 3.7 source cls._num_runs_pending = 0 cls._is_proactorloop = ( os.name == 'nt' and issubclass(cls, asyncio.ProactorEventLoop)) if sys.version_info < (3, 7, 0): cls._set_coroutine_origin_tracking = cls._set_coroutine_wrapper cls._nest_patched = True def _patch_task(): """Patch the Task's step and enter/leave methods to make it reentrant.""" def step(task, exc=None): curr_task = curr_tasks.get(task._loop) try: step_orig(task, exc) finally: if curr_task is None: curr_tasks.pop(task._loop, None) else: curr_tasks[task._loop] = curr_task Task = asyncio.Task if hasattr(Task, '_nest_patched'): return if sys.version_info >= (3, 7, 0): def enter_task(loop, task): curr_tasks[loop] = task def leave_task(loop, task): curr_tasks.pop(loop, None) asyncio.tasks._enter_task = enter_task asyncio.tasks._leave_task = leave_task curr_tasks = asyncio.tasks._current_tasks step_orig = Task._Task__step Task._Task__step = step else: curr_tasks = Task._current_tasks step_orig = Task._step Task._step = step Task._nest_patched = True def _patch_tornado(): """ If tornado is imported before nest_asyncio, make tornado aware of the pure-Python asyncio Future. """ if 'tornado' in sys.modules: import tornado.concurrent as tc # type: ignore tc.Future = asyncio.Future if asyncio.Future not in tc.FUTURES: tc.FUTURES += (asyncio.Future,) The provided code snippet includes necessary dependencies for implementing the `apply` function. Write a Python function `def apply(loop=None)` to solve the following problem: Patch asyncio to make its event loop reentrant. Here is the function: def apply(loop=None): """Patch asyncio to make its event loop reentrant.""" _patch_asyncio() _patch_task() _patch_tornado() loop = loop or asyncio.get_event_loop() _patch_loop(loop)
Patch asyncio to make its event loop reentrant.
176,204
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `convert_dos_path` function. Write a Python function `def convert_dos_path(s)` to solve the following problem: r"""Convert paths using native DOS format like: "\Device\HarddiskVolume1\Windows\systemew\file.txt" into: "C:\Windows\systemew\file.txt" Here is the function: def convert_dos_path(s): r"""Convert paths using native DOS format like: "\Device\HarddiskVolume1\Windows\systemew\file.txt" into: "C:\Windows\systemew\file.txt" """ rawdrive = '\\'.join(s.split('\\')[:3]) driveletter = cext.QueryDosDevice(rawdrive) remainder = s[len(rawdrive):] return os.path.join(driveletter, remainder)
r"""Convert paths using native DOS format like: "\Device\HarddiskVolume1\Windows\systemew\file.txt" into: "C:\Windows\systemew\file.txt"
176,205
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def getpagesize(): return cext.getpagesize()
null
176,206
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `virtual_memory` function. Write a Python function `def virtual_memory()` to solve the following problem: System virtual memory as a namedtuple. Here is the function: def virtual_memory(): """System virtual memory as a namedtuple.""" mem = cext.virtual_mem() totphys, availphys, totsys, availsys = mem # total = totphys avail = availphys free = availphys used = total - avail percent = usage_percent((total - avail), total, round_=1) return svmem(total, avail, percent, used, free)
System virtual memory as a namedtuple.
176,207
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `swap_memory` function. Write a Python function `def swap_memory()` to solve the following problem: Swap system memory as a (total, used, free, sin, sout) tuple. Here is the function: def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" mem = cext.virtual_mem() total_phys = mem[0] free_phys = mem[1] total_system = mem[2] free_system = mem[3] # system memory (commit total/limit) is the sum of physical and swap # thus physical memory values need to be substracted to get swap values total = total_system - total_phys free = min(total, free_system - free_phys) used = total - free percent = usage_percent(used, total, round_=1) return _common.sswap(total, used, free, percent, 0, 0)
Swap system memory as a (total, used, free, sin, sout) tuple.
176,208
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS ENCODING = sys.getfilesystemencoding() def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret PY3 = sys.version_info[0] == 3 if PY3: long = int xrange = range unicode = str basestring = str range = range def u(s): return s def b(s): return s.encode("latin-1") else: long = long range = xrange unicode = unicode basestring = basestring def u(s): return unicode(s, "unicode_escape") def b(s): return s if PY3: super = super else: _builtin_super = super def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1): """Like Python 3 builtin super(). If called without any arguments it attempts to infer them at runtime. """ if type_ is _SENTINEL: f = sys._getframe(framedepth) try: # Get the function's first positional argument. type_or_obj = f.f_locals[f.f_code.co_varnames[0]] except (IndexError, KeyError): raise RuntimeError('super() used in a function with no args') try: # Get the MRO so we can crawl it. mro = type_or_obj.__mro__ except (AttributeError, RuntimeError): try: mro = type_or_obj.__class__.__mro__ except AttributeError: raise RuntimeError('super() used in a non-newstyle class') for type_ in mro: # Find the class that owns the currently-executing method. for meth in type_.__dict__.values(): # Drill down through any wrappers to the underlying func. # This handles e.g. classmethod() and staticmethod(). try: while not isinstance(meth, types.FunctionType): if isinstance(meth, property): # Calling __get__ on the property will invoke # user code which might throw exceptions or # have side effects meth = meth.fget else: try: meth = meth.__func__ except AttributeError: meth = meth.__get__(type_or_obj, type_) except (AttributeError, TypeError): continue if meth.func_code is f.f_code: break # found else: # Not found. Move onto the next class in MRO. continue break # found else: raise RuntimeError('super() called outside a method') # Dispatch to builtin super(). if type_or_obj is not _SENTINEL: return _builtin_super(type_, type_or_obj) return _builtin_super(type_) if PY3: FileNotFoundError = FileNotFoundError # NOQA PermissionError = PermissionError # NOQA ProcessLookupError = ProcessLookupError # NOQA InterruptedError = InterruptedError # NOQA ChildProcessError = ChildProcessError # NOQA FileExistsError = FileExistsError # NOQA else: # https://github.com/PythonCharmers/python-future/blob/exceptions/ # src/future/types/exceptions/pep3151.py import platform def _instance_checking_exception(base_exception=Exception): def wrapped(instance_checker): class TemporaryClass(base_exception): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], TemporaryClass): unwrap_me = args[0] for attr in dir(unwrap_me): if not attr.startswith('__'): setattr(self, attr, getattr(unwrap_me, attr)) else: super(TemporaryClass, self).__init__(*args, **kwargs) class __metaclass__(type): def __instancecheck__(cls, inst): return instance_checker(inst) def __subclasscheck__(cls, classinfo): value = sys.exc_info()[1] return isinstance(value, cls) TemporaryClass.__name__ = instance_checker.__name__ TemporaryClass.__doc__ = instance_checker.__doc__ return TemporaryClass return wrapped def FileNotFoundError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT def ProcessLookupError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH def PermissionError(inst): return getattr(inst, 'errno', _SENTINEL) in ( errno.EACCES, errno.EPERM) def InterruptedError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EINTR def ChildProcessError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD def FileExistsError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST if platform.python_implementation() != "CPython": try: raise OSError(errno.EEXIST, "perm") except FileExistsError: pass except OSError: raise RuntimeError( "broken or incompatible Python implementation, see: " "https://github.com/giampaolo/psutil/issues/1659") The provided code snippet includes necessary dependencies for implementing the `disk_usage` function. Write a Python function `def disk_usage(path)` to solve the following problem: Return disk usage associated with path. Here is the function: def disk_usage(path): """Return disk usage associated with path.""" if PY3 and isinstance(path, bytes): # XXX: do we want to use "strict"? Probably yes, in order # to fail immediately. After all we are accepting input here... path = path.decode(ENCODING, errors="strict") total, free = cext.disk_usage(path) used = total - free percent = usage_percent(used, total, round_=1) return _common.sdiskusage(total, used, free, percent)
Return disk usage associated with path.
176,209
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `disk_partitions` function. Write a Python function `def disk_partitions(all)` to solve the following problem: Return disk partitions. Here is the function: def disk_partitions(all): """Return disk partitions.""" rawlist = cext.disk_partitions(all) return [_common.sdiskpart(*x) for x in rawlist]
Return disk partitions.
176,210
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'interrupt', 'dpc']) def per_cpu_times(): """Return system per-CPU times as a list of named tuples.""" ret = [] for user, system, idle, interrupt, dpc in cext.per_cpu_times(): item = scputimes(user, system, idle, interrupt, dpc) ret.append(item) return ret The provided code snippet includes necessary dependencies for implementing the `cpu_times` function. Write a Python function `def cpu_times()` to solve the following problem: Return system CPU times as a named tuple. Here is the function: def cpu_times(): """Return system CPU times as a named tuple.""" user, system, idle = cext.cpu_times() # Internally, GetSystemTimes() is used, and it doesn't return # interrupt and dpc times. cext.per_cpu_times() does, so we # rely on it to get those only. percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())]) return scputimes(user, system, idle, percpu_summed.interrupt, percpu_summed.dpc)
Return system CPU times as a named tuple.
176,211
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `cpu_count_logical` function. Write a Python function `def cpu_count_logical()` to solve the following problem: Return the number of logical CPUs in the system. Here is the function: def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical()
Return the number of logical CPUs in the system.
176,212
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `cpu_count_cores` function. Write a Python function `def cpu_count_cores()` to solve the following problem: Return the number of CPU cores in the system. Here is the function: def cpu_count_cores(): """Return the number of CPU cores in the system.""" return cext.cpu_count_cores()
Return the number of CPU cores in the system.
176,213
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `cpu_stats` function. Write a Python function `def cpu_stats()` to solve the following problem: Return CPU statistics. Here is the function: def cpu_stats(): """Return CPU statistics.""" ctx_switches, interrupts, dpcs, syscalls = cext.cpu_stats() soft_interrupts = 0 return _common.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
Return CPU statistics.
176,214
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `cpu_freq` function. Write a Python function `def cpu_freq()` to solve the following problem: Return CPU frequency. On Windows per-cpu frequency is not supported. Here is the function: def cpu_freq(): """Return CPU frequency. On Windows per-cpu frequency is not supported. """ curr, max_ = cext.cpu_freq() min_ = 0.0 return [_common.scpufreq(float(curr), min_, float(max_))]
Return CPU frequency. On Windows per-cpu frequency is not supported.
176,215
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS _loadavg_inititialized = False The provided code snippet includes necessary dependencies for implementing the `getloadavg` function. Write a Python function `def getloadavg()` to solve the following problem: Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes respectively as a tuple Here is the function: def getloadavg(): """Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes respectively as a tuple""" global _loadavg_inititialized if not _loadavg_inititialized: cext.init_loadavg_counter() _loadavg_inititialized = True # Drop to 2 decimal points which is what Linux does raw_loads = cext.getloadavg() return tuple([round(load, 2) for load in raw_loads])
Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes respectively as a tuple
176,216
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS TCP_STATUSES = { cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED, cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT, cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV, cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1, cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2, cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT, cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE, cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK, cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN, cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING, cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB, cext.PSUTIL_CONN_NONE: _common.CONN_NONE, } conn_tmap = { "all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]), "tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]), "tcp4": ([AF_INET], [SOCK_STREAM]), "udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]), "udp4": ([AF_INET], [SOCK_DGRAM]), "inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]), "inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]), "inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]), } def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None): """Convert a raw connection tuple to a proper ntuple.""" if fam in (socket.AF_INET, AF_INET6): if laddr: laddr = addr(*laddr) if raddr: raddr = addr(*raddr) if type_ == socket.SOCK_STREAM and fam in (AF_INET, AF_INET6): status = status_map.get(status, CONN_NONE) else: status = CONN_NONE # ignore whatever C returned to us fam = sockfam_to_enum(fam) type_ = socktype_to_enum(type_) if pid is None: return pconn(fd, fam, type_, laddr, raddr, status) else: return sconn(fd, fam, type_, laddr, raddr, status, pid) The provided code snippet includes necessary dependencies for implementing the `net_connections` function. Write a Python function `def net_connections(kind, _pid=-1)` to solve the following problem: Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). Here is the function: def net_connections(kind, _pid=-1): """Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). """ if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.net_connections(_pid, families, types) ret = set() for item in rawlist: fd, fam, type, laddr, raddr, status, pid = item nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid=pid if _pid == -1 else None) ret.add(nt) return list(ret)
Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only).
176,217
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def py2_strencode(s): """Encode a unicode string to a byte string by using the default fs encoding + "replace" error handler. """ if PY3: return s else: if isinstance(s, str): return s else: return s.encode(ENCODING, ENCODING_ERRS) PY3 = sys.version_info[0] == 3 if PY3: long = int xrange = range unicode = str basestring = str range = range def u(s): return s def b(s): return s.encode("latin-1") else: long = long range = xrange unicode = unicode basestring = basestring def u(s): return unicode(s, "unicode_escape") def b(s): return s if PY3: super = super else: _builtin_super = super def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1): """Like Python 3 builtin super(). If called without any arguments it attempts to infer them at runtime. """ if type_ is _SENTINEL: f = sys._getframe(framedepth) try: # Get the function's first positional argument. type_or_obj = f.f_locals[f.f_code.co_varnames[0]] except (IndexError, KeyError): raise RuntimeError('super() used in a function with no args') try: # Get the MRO so we can crawl it. mro = type_or_obj.__mro__ except (AttributeError, RuntimeError): try: mro = type_or_obj.__class__.__mro__ except AttributeError: raise RuntimeError('super() used in a non-newstyle class') for type_ in mro: # Find the class that owns the currently-executing method. for meth in type_.__dict__.values(): # Drill down through any wrappers to the underlying func. # This handles e.g. classmethod() and staticmethod(). try: while not isinstance(meth, types.FunctionType): if isinstance(meth, property): # Calling __get__ on the property will invoke # user code which might throw exceptions or # have side effects meth = meth.fget else: try: meth = meth.__func__ except AttributeError: meth = meth.__get__(type_or_obj, type_) except (AttributeError, TypeError): continue if meth.func_code is f.f_code: break # found else: # Not found. Move onto the next class in MRO. continue break # found else: raise RuntimeError('super() called outside a method') # Dispatch to builtin super(). if type_or_obj is not _SENTINEL: return _builtin_super(type_, type_or_obj) return _builtin_super(type_) if PY3: FileNotFoundError = FileNotFoundError # NOQA PermissionError = PermissionError # NOQA ProcessLookupError = ProcessLookupError # NOQA InterruptedError = InterruptedError # NOQA ChildProcessError = ChildProcessError # NOQA FileExistsError = FileExistsError # NOQA else: # https://github.com/PythonCharmers/python-future/blob/exceptions/ # src/future/types/exceptions/pep3151.py import platform def _instance_checking_exception(base_exception=Exception): def wrapped(instance_checker): class TemporaryClass(base_exception): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], TemporaryClass): unwrap_me = args[0] for attr in dir(unwrap_me): if not attr.startswith('__'): setattr(self, attr, getattr(unwrap_me, attr)) else: super(TemporaryClass, self).__init__(*args, **kwargs) class __metaclass__(type): def __instancecheck__(cls, inst): return instance_checker(inst) def __subclasscheck__(cls, classinfo): value = sys.exc_info()[1] return isinstance(value, cls) TemporaryClass.__name__ = instance_checker.__name__ TemporaryClass.__doc__ = instance_checker.__doc__ return TemporaryClass return wrapped def FileNotFoundError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT def ProcessLookupError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH def PermissionError(inst): return getattr(inst, 'errno', _SENTINEL) in ( errno.EACCES, errno.EPERM) def InterruptedError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EINTR def ChildProcessError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD def FileExistsError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST if platform.python_implementation() != "CPython": try: raise OSError(errno.EEXIST, "perm") except FileExistsError: pass except OSError: raise RuntimeError( "broken or incompatible Python implementation, see: " "https://github.com/giampaolo/psutil/issues/1659") The provided code snippet includes necessary dependencies for implementing the `net_if_stats` function. Write a Python function `def net_if_stats()` to solve the following problem: Get NIC stats (isup, duplex, speed, mtu). Here is the function: def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" ret = {} rawdict = cext.net_if_stats() for name, items in rawdict.items(): if not PY3: assert isinstance(name, unicode), type(name) name = py2_strencode(name) isup, duplex, speed, mtu = items if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) ret[name] = _common.snicstats(isup, duplex, speed, mtu, '') return ret
Get NIC stats (isup, duplex, speed, mtu).
176,218
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def py2_strencode(s): """Encode a unicode string to a byte string by using the default fs encoding + "replace" error handler. """ if PY3: return s else: if isinstance(s, str): return s else: return s.encode(ENCODING, ENCODING_ERRS) The provided code snippet includes necessary dependencies for implementing the `net_io_counters` function. Write a Python function `def net_io_counters()` to solve the following problem: Return network I/O statistics for every network interface installed on the system as a dict of raw tuples. Here is the function: def net_io_counters(): """Return network I/O statistics for every network interface installed on the system as a dict of raw tuples. """ ret = cext.net_io_counters() return dict([(py2_strencode(k), v) for k, v in ret.items()])
Return network I/O statistics for every network interface installed on the system as a dict of raw tuples.
176,219
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def py2_strencode(s): """Encode a unicode string to a byte string by using the default fs encoding + "replace" error handler. """ if PY3: return s else: if isinstance(s, str): return s else: return s.encode(ENCODING, ENCODING_ERRS) The provided code snippet includes necessary dependencies for implementing the `net_if_addrs` function. Write a Python function `def net_if_addrs()` to solve the following problem: Return the addresses associated to each NIC. Here is the function: def net_if_addrs(): """Return the addresses associated to each NIC.""" ret = [] for items in cext.net_if_addrs(): items = list(items) items[0] = py2_strencode(items[0]) ret.append(items) return ret
Return the addresses associated to each NIC.
176,220
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS The provided code snippet includes necessary dependencies for implementing the `sensors_battery` function. Write a Python function `def sensors_battery()` to solve the following problem: Return battery information. Here is the function: def sensors_battery(): """Return battery information.""" # For constants meaning see: # https://msdn.microsoft.com/en-us/library/windows/desktop/ # aa373232(v=vs.85).aspx acline_status, flags, percent, secsleft = cext.sensors_battery() power_plugged = acline_status == 1 no_battery = bool(flags & 128) charging = bool(flags & 8) if no_battery: return None if power_plugged or charging: secsleft = _common.POWER_TIME_UNLIMITED elif secsleft == -1: secsleft = _common.POWER_TIME_UNKNOWN return _common.sbattery(percent, secsleft, power_plugged)
Return battery information.
176,221
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS _last_btime = 0 The provided code snippet includes necessary dependencies for implementing the `boot_time` function. Write a Python function `def boot_time()` to solve the following problem: The system boot time expressed in seconds since the epoch. Here is the function: def boot_time(): """The system boot time expressed in seconds since the epoch.""" # This dirty hack is to adjust the precision of the returned # value which may have a 1 second fluctuation, see: # https://github.com/giampaolo/psutil/issues/1007 global _last_btime ret = float(cext.boot_time()) if abs(ret - _last_btime) <= 1: return _last_btime else: _last_btime = ret return ret
The system boot time expressed in seconds since the epoch.
176,222
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def py2_strencode(s): """Encode a unicode string to a byte string by using the default fs encoding + "replace" error handler. """ if PY3: return s else: if isinstance(s, str): return s else: return s.encode(ENCODING, ENCODING_ERRS) The provided code snippet includes necessary dependencies for implementing the `users` function. Write a Python function `def users()` to solve the following problem: Return currently connected users as a list of namedtuples. Here is the function: def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() for item in rawlist: user, hostname, tstamp = item user = py2_strencode(user) nt = _common.suser(user, None, hostname, tstamp, None) retlist.append(nt) return retlist
Return currently connected users as a list of namedtuples.
176,223
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def py2_strencode(s): """Encode a unicode string to a byte string by using the default fs encoding + "replace" error handler. """ if PY3: return s else: if isinstance(s, str): return s else: return s.encode(ENCODING, ENCODING_ERRS) class WindowsService(object): """Represents an installed Windows service.""" def __init__(self, name, display_name): self._name = name self._display_name = display_name def __str__(self): details = "(name=%r, display_name=%r)" % ( self._name, self._display_name) return "%s%s" % (self.__class__.__name__, details) def __repr__(self): return "<%s at %s>" % (self.__str__(), id(self)) def __eq__(self, other): # Test for equality with another WindosService object based # on name. if not isinstance(other, WindowsService): return NotImplemented return self._name == other._name def __ne__(self, other): return not self == other def _query_config(self): with self._wrap_exceptions(): display_name, binpath, username, start_type = \ cext.winservice_query_config(self._name) # XXX - update _self.display_name? return dict( display_name=py2_strencode(display_name), binpath=py2_strencode(binpath), username=py2_strencode(username), start_type=py2_strencode(start_type)) def _query_status(self): with self._wrap_exceptions(): status, pid = cext.winservice_query_status(self._name) if pid == 0: pid = None return dict(status=status, pid=pid) def _wrap_exceptions(self): """Ctx manager which translates bare OSError and WindowsError exceptions into NoSuchProcess and AccessDenied. """ try: yield except OSError as err: if is_permission_err(err): raise AccessDenied( pid=None, name=self._name, msg="service %r is not querable (not enough privileges)" % self._name) elif err.winerror in (cext.ERROR_INVALID_NAME, cext.ERROR_SERVICE_DOES_NOT_EXIST): raise NoSuchProcess( pid=None, name=self._name, msg="service %r does not exist)" % self._name) else: raise # config query def name(self): """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. """ return self._name def display_name(self): """The service display name. The value is cached when this class is instantiated. """ return self._display_name def binpath(self): """The fully qualified path to the service binary/exe file as a string, including command line arguments. """ return self._query_config()['binpath'] def username(self): """The name of the user that owns this service.""" return self._query_config()['username'] def start_type(self): """A string which can either be "automatic", "manual" or "disabled". """ return self._query_config()['start_type'] # status query def pid(self): """The process PID, if any, else None. This can be passed to Process class to control the service's process. """ return self._query_status()['pid'] def status(self): """Service status as a string.""" return self._query_status()['status'] def description(self): """Service long description.""" return py2_strencode(cext.winservice_query_descr(self.name())) # utils def as_dict(self): """Utility method retrieving all the information above as a dictionary. """ 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 # actions # XXX: the necessary C bindings for start() and stop() are # implemented but for now I prefer not to expose them. # I may change my mind in the future. Reasons: # - they require Administrator privileges # - can't implement a timeout for stop() (unless by using a thread, # which sucks) # - would require adding ServiceAlreadyStarted and # ServiceAlreadyStopped exceptions, adding two new APIs. # - we might also want to have modify(), which would basically mean # rewriting win32serviceutil.ChangeServiceConfig, which involves a # lot of stuff (and API constants which would pollute the API), see: # http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/ # win32/lib/win32serviceutil.py.html#0175 # - psutil is typically about "read only" monitoring stuff; # win_service_* APIs should only be used to retrieve a service and # check whether it's running # def start(self, timeout=None): # with self._wrap_exceptions(): # cext.winservice_start(self.name()) # if timeout: # giveup_at = time.time() + timeout # while True: # if self.status() == "running": # return # else: # if time.time() > giveup_at: # raise TimeoutExpired(timeout) # else: # time.sleep(.1) # def stop(self): # # Note: timeout is not implemented because it's just not # # possible, see: # # http://stackoverflow.com/questions/11973228/ # with self._wrap_exceptions(): # return cext.winservice_stop(self.name()) The provided code snippet includes necessary dependencies for implementing the `win_service_iter` function. Write a Python function `def win_service_iter()` to solve the following problem: Yields a list of WindowsService instances. Here is the function: def win_service_iter(): """Yields a list of WindowsService instances.""" for name, display_name in cext.winservice_enumerate(): yield WindowsService(py2_strencode(name), py2_strencode(display_name))
Yields a list of WindowsService instances.
176,224
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS class WindowsService(object): """Represents an installed Windows service.""" def __init__(self, name, display_name): self._name = name self._display_name = display_name def __str__(self): details = "(name=%r, display_name=%r)" % ( self._name, self._display_name) return "%s%s" % (self.__class__.__name__, details) def __repr__(self): return "<%s at %s>" % (self.__str__(), id(self)) def __eq__(self, other): # Test for equality with another WindosService object based # on name. if not isinstance(other, WindowsService): return NotImplemented return self._name == other._name def __ne__(self, other): return not self == other def _query_config(self): with self._wrap_exceptions(): display_name, binpath, username, start_type = \ cext.winservice_query_config(self._name) # XXX - update _self.display_name? return dict( display_name=py2_strencode(display_name), binpath=py2_strencode(binpath), username=py2_strencode(username), start_type=py2_strencode(start_type)) def _query_status(self): with self._wrap_exceptions(): status, pid = cext.winservice_query_status(self._name) if pid == 0: pid = None return dict(status=status, pid=pid) def _wrap_exceptions(self): """Ctx manager which translates bare OSError and WindowsError exceptions into NoSuchProcess and AccessDenied. """ try: yield except OSError as err: if is_permission_err(err): raise AccessDenied( pid=None, name=self._name, msg="service %r is not querable (not enough privileges)" % self._name) elif err.winerror in (cext.ERROR_INVALID_NAME, cext.ERROR_SERVICE_DOES_NOT_EXIST): raise NoSuchProcess( pid=None, name=self._name, msg="service %r does not exist)" % self._name) else: raise # config query def name(self): """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. """ return self._name def display_name(self): """The service display name. The value is cached when this class is instantiated. """ return self._display_name def binpath(self): """The fully qualified path to the service binary/exe file as a string, including command line arguments. """ return self._query_config()['binpath'] def username(self): """The name of the user that owns this service.""" return self._query_config()['username'] def start_type(self): """A string which can either be "automatic", "manual" or "disabled". """ return self._query_config()['start_type'] # status query def pid(self): """The process PID, if any, else None. This can be passed to Process class to control the service's process. """ return self._query_status()['pid'] def status(self): """Service status as a string.""" return self._query_status()['status'] def description(self): """Service long description.""" return py2_strencode(cext.winservice_query_descr(self.name())) # utils def as_dict(self): """Utility method retrieving all the information above as a dictionary. """ 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 # actions # XXX: the necessary C bindings for start() and stop() are # implemented but for now I prefer not to expose them. # I may change my mind in the future. Reasons: # - they require Administrator privileges # - can't implement a timeout for stop() (unless by using a thread, # which sucks) # - would require adding ServiceAlreadyStarted and # ServiceAlreadyStopped exceptions, adding two new APIs. # - we might also want to have modify(), which would basically mean # rewriting win32serviceutil.ChangeServiceConfig, which involves a # lot of stuff (and API constants which would pollute the API), see: # http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/ # win32/lib/win32serviceutil.py.html#0175 # - psutil is typically about "read only" monitoring stuff; # win_service_* APIs should only be used to retrieve a service and # check whether it's running # def start(self, timeout=None): # with self._wrap_exceptions(): # cext.winservice_start(self.name()) # if timeout: # giveup_at = time.time() + timeout # while True: # if self.status() == "running": # return # else: # if time.time() > giveup_at: # raise TimeoutExpired(timeout) # else: # time.sleep(.1) # def stop(self): # # Note: timeout is not implemented because it's just not # # possible, see: # # http://stackoverflow.com/questions/11973228/ # with self._wrap_exceptions(): # return cext.winservice_stop(self.name()) The provided code snippet includes necessary dependencies for implementing the `win_service_get` function. Write a Python function `def win_service_get(name)` to solve the following problem: Open a Windows service and return it as a WindowsService instance. Here is the function: def win_service_get(name): """Open a Windows service and return it as a WindowsService instance.""" service = WindowsService(name, None) service._display_name = service._query_config()['display_name'] return service
Open a Windows service and return it as a WindowsService instance.
176,225
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS def convert_oserror(exc, pid=None, name=None): """Convert OSError into NoSuchProcess or AccessDenied.""" assert isinstance(exc, OSError), exc if is_permission_err(exc): return AccessDenied(pid=pid, name=name) if exc.errno == errno.ESRCH: return NoSuchProcess(pid=pid, name=name) raise exc The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions` function. Write a Python function `def wrap_exceptions(fun)` to solve the following problem: Decorator which converts OSError into NoSuchProcess or AccessDenied. Here is the function: def wrap_exceptions(fun): """Decorator which converts OSError into NoSuchProcess or AccessDenied.""" @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: raise convert_oserror(err, pid=self.pid, name=self._name) return wrapper
Decorator which converts OSError into NoSuchProcess or AccessDenied.
176,226
import contextlib import errno import functools import os import signal import sys import time from collections import namedtuple from . import _common from ._common import ENCODING from ._common import ENCODING_ERRS from ._common import AccessDenied from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import debug from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PY3 from ._compat import long from ._compat import lru_cache from ._compat import range from ._compat import unicode from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS from ._psutil_windows import HIGH_PRIORITY_CLASS from ._psutil_windows import IDLE_PRIORITY_CLASS from ._psutil_windows import NORMAL_PRIORITY_CLASS from ._psutil_windows import REALTIME_PRIORITY_CLASS ERROR_PARTIAL_COPY = 299 class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `retry_error_partial_copy` function. Write a Python function `def retry_error_partial_copy(fun)` to solve the following problem: Workaround for https://github.com/giampaolo/psutil/issues/875. See: https://stackoverflow.com/questions/4457745#4457745 Here is the function: def retry_error_partial_copy(fun): """Workaround for https://github.com/giampaolo/psutil/issues/875. See: https://stackoverflow.com/questions/4457745#4457745 """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): delay = 0.0001 times = 33 for x in range(times): # retries for roughly 1 second try: return fun(self, *args, **kwargs) except WindowsError as _: err = _ if err.winerror == ERROR_PARTIAL_COPY: time.sleep(delay) delay = min(delay * 2, 0.04) continue else: raise else: msg = "%s retried %s times, converted to AccessDenied as it's " \ "still returning %r" % (fun, times, err) raise AccessDenied(pid=self.pid, name=self._name, msg=msg) return wrapper
Workaround for https://github.com/giampaolo/psutil/issues/875. See: https://stackoverflow.com/questions/4457745#4457745
176,227
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret def virtual_memory(): total, avail, free, pinned, inuse = cext.virtual_mem() percent = usage_percent((total - avail), total, round_=1) return svmem(total, avail, percent, inuse, free)
null
176,228
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `swap_memory` function. Write a Python function `def swap_memory()` to solve the following problem: Swap system memory as a (total, used, free, sin, sout) tuple. Here is the function: def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, free, sin, sout = cext.swap_mem() used = total - free percent = usage_percent(used, total, round_=1) return _common.sswap(total, used, free, percent, sin, sout)
Swap system memory as a (total, used, free, sin, sout) tuple.
176,229
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait']) def per_cpu_times(): """Return system per-CPU times as a list of named tuples""" ret = cext.per_cpu_times() return [scputimes(*x) for x in ret] The provided code snippet includes necessary dependencies for implementing the `cpu_times` function. Write a Python function `def cpu_times()` to solve the following problem: Return system-wide CPU times as a named tuple Here is the function: def cpu_times(): """Return system-wide CPU times as a named tuple""" ret = cext.per_cpu_times() return scputimes(*[sum(x) for x in zip(*ret)])
Return system-wide CPU times as a named tuple
176,230
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `cpu_count_logical` function. Write a Python function `def cpu_count_logical()` to solve the following problem: Return the number of logical CPUs in the system. Here is the function: def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: # mimic os.cpu_count() behavior return None
Return the number of logical CPUs in the system.
176,231
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError import sys if sys.version_info[0] < 3: del num, x PY3 = sys.version_info[0] == 3 if PY3: long = int xrange = range unicode = str basestring = str range = range def u(s): return s def b(s): return s.encode("latin-1") else: long = long range = xrange unicode = unicode basestring = basestring def u(s): return unicode(s, "unicode_escape") def b(s): return s if PY3: super = super else: _builtin_super = super def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1): """Like Python 3 builtin super(). If called without any arguments it attempts to infer them at runtime. """ if type_ is _SENTINEL: f = sys._getframe(framedepth) try: # Get the function's first positional argument. type_or_obj = f.f_locals[f.f_code.co_varnames[0]] except (IndexError, KeyError): raise RuntimeError('super() used in a function with no args') try: # Get the MRO so we can crawl it. mro = type_or_obj.__mro__ except (AttributeError, RuntimeError): try: mro = type_or_obj.__class__.__mro__ except AttributeError: raise RuntimeError('super() used in a non-newstyle class') for type_ in mro: # Find the class that owns the currently-executing method. for meth in type_.__dict__.values(): # Drill down through any wrappers to the underlying func. # This handles e.g. classmethod() and staticmethod(). try: while not isinstance(meth, types.FunctionType): if isinstance(meth, property): # Calling __get__ on the property will invoke # user code which might throw exceptions or # have side effects meth = meth.fget else: try: meth = meth.__func__ except AttributeError: meth = meth.__get__(type_or_obj, type_) except (AttributeError, TypeError): continue if meth.func_code is f.f_code: break # found else: # Not found. Move onto the next class in MRO. continue break # found else: raise RuntimeError('super() called outside a method') # Dispatch to builtin super(). if type_or_obj is not _SENTINEL: return _builtin_super(type_, type_or_obj) return _builtin_super(type_) if PY3: FileNotFoundError = FileNotFoundError # NOQA PermissionError = PermissionError # NOQA ProcessLookupError = ProcessLookupError # NOQA InterruptedError = InterruptedError # NOQA ChildProcessError = ChildProcessError # NOQA FileExistsError = FileExistsError # NOQA else: # https://github.com/PythonCharmers/python-future/blob/exceptions/ # src/future/types/exceptions/pep3151.py import platform def _instance_checking_exception(base_exception=Exception): def wrapped(instance_checker): class TemporaryClass(base_exception): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], TemporaryClass): unwrap_me = args[0] for attr in dir(unwrap_me): if not attr.startswith('__'): setattr(self, attr, getattr(unwrap_me, attr)) else: super(TemporaryClass, self).__init__(*args, **kwargs) class __metaclass__(type): def __instancecheck__(cls, inst): return instance_checker(inst) def __subclasscheck__(cls, classinfo): value = sys.exc_info()[1] return isinstance(value, cls) TemporaryClass.__name__ = instance_checker.__name__ TemporaryClass.__doc__ = instance_checker.__doc__ return TemporaryClass return wrapped def FileNotFoundError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT def ProcessLookupError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH def PermissionError(inst): return getattr(inst, 'errno', _SENTINEL) in ( errno.EACCES, errno.EPERM) def InterruptedError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EINTR def ChildProcessError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD def FileExistsError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST if platform.python_implementation() != "CPython": try: raise OSError(errno.EEXIST, "perm") except FileExistsError: pass except OSError: raise RuntimeError( "broken or incompatible Python implementation, see: " "https://github.com/giampaolo/psutil/issues/1659") def cpu_count_cores(): cmd = "lsdev -Cc processor" 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: raise RuntimeError("%r command error\n%s" % (cmd, stderr)) processors = stdout.strip().splitlines() return len(processors) or None
null
176,232
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `cpu_stats` function. Write a Python function `def cpu_stats()` to solve the following problem: Return various CPU stats as a named tuple. Here is the function: def cpu_stats(): """Return various CPU stats as a named tuple.""" ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats() return _common.scpustats( ctx_switches, interrupts, soft_interrupts, syscalls)
Return various CPU stats as a named tuple.
176,233
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError disk_usage = _psposix.disk_usage The provided code snippet includes necessary dependencies for implementing the `disk_partitions` function. Write a Python function `def disk_partitions(all=False)` to solve the following problem: Return system disk partitions. Here is the function: def disk_partitions(all=False): """Return system disk partitions.""" # TODO - the filtering logic should be better checked so that # it tries to reflect 'df' as much as possible retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: # Differently from, say, Linux, we don't have a list of # common fs types so the best we can do, AFAIK, is to # filter by filesystem having a total size > 0. if not disk_usage(mountpoint).total: continue maxfile = maxpath = None # set later ntuple = _common.sdiskpart(device, mountpoint, fstype, opts, maxfile, maxpath) retlist.append(ntuple) return retlist
Return system disk partitions.
176,234
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError TCP_STATUSES = { cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV, cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, cext.TCPS_CLOSED: _common.CONN_CLOSE, cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, cext.TCPS_LISTEN: _common.CONN_LISTEN, cext.TCPS_CLOSING: _common.CONN_CLOSING, cext.PSUTIL_CONN_NONE: _common.CONN_NONE, } def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None): """Convert a raw connection tuple to a proper ntuple.""" if fam in (socket.AF_INET, AF_INET6): if laddr: laddr = addr(*laddr) if raddr: raddr = addr(*raddr) if type_ == socket.SOCK_STREAM and fam in (AF_INET, AF_INET6): status = status_map.get(status, CONN_NONE) else: status = CONN_NONE # ignore whatever C returned to us fam = sockfam_to_enum(fam) type_ = socktype_to_enum(type_) if pid is None: return pconn(fd, fam, type_, laddr, raddr, status) else: return sconn(fd, fam, type_, laddr, raddr, status, pid) The provided code snippet includes necessary dependencies for implementing the `net_connections` function. Write a Python function `def net_connections(kind, _pid=-1)` to solve the following problem: Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). Here is the function: def net_connections(kind, _pid=-1): """Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). """ cmap = _common.conn_tmap if kind not in cmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in cmap]))) families, types = _common.conn_tmap[kind] rawlist = cext.net_connections(_pid) ret = [] for item in rawlist: fd, fam, type_, laddr, raddr, status, pid = item if fam not in families: continue if type_ not in types: continue nt = conn_to_ntuple(fd, fam, type_, laddr, raddr, status, TCP_STATUSES, pid=pid if _pid == -1 else None) ret.append(nt) return ret
Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only).
176,235
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError net_if_addrs = cext_posix.net_if_addrs import sys if sys.version_info[0] < 3: del num, x PY3 = sys.version_info[0] == 3 if PY3: long = int xrange = range unicode = str basestring = str range = range def u(s): return s def b(s): return s.encode("latin-1") else: long = long range = xrange unicode = unicode basestring = basestring def u(s): return unicode(s, "unicode_escape") def b(s): return s if PY3: super = super else: _builtin_super = super def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1): """Like Python 3 builtin super(). If called without any arguments it attempts to infer them at runtime. """ if type_ is _SENTINEL: f = sys._getframe(framedepth) try: # Get the function's first positional argument. type_or_obj = f.f_locals[f.f_code.co_varnames[0]] except (IndexError, KeyError): raise RuntimeError('super() used in a function with no args') try: # Get the MRO so we can crawl it. mro = type_or_obj.__mro__ except (AttributeError, RuntimeError): try: mro = type_or_obj.__class__.__mro__ except AttributeError: raise RuntimeError('super() used in a non-newstyle class') for type_ in mro: # Find the class that owns the currently-executing method. for meth in type_.__dict__.values(): # Drill down through any wrappers to the underlying func. # This handles e.g. classmethod() and staticmethod(). try: while not isinstance(meth, types.FunctionType): if isinstance(meth, property): # Calling __get__ on the property will invoke # user code which might throw exceptions or # have side effects meth = meth.fget else: try: meth = meth.__func__ except AttributeError: meth = meth.__get__(type_or_obj, type_) except (AttributeError, TypeError): continue if meth.func_code is f.f_code: break # found else: # Not found. Move onto the next class in MRO. continue break # found else: raise RuntimeError('super() called outside a method') # Dispatch to builtin super(). if type_or_obj is not _SENTINEL: return _builtin_super(type_, type_or_obj) return _builtin_super(type_) if PY3: FileNotFoundError = FileNotFoundError # NOQA PermissionError = PermissionError # NOQA ProcessLookupError = ProcessLookupError # NOQA InterruptedError = InterruptedError # NOQA ChildProcessError = ChildProcessError # NOQA FileExistsError = FileExistsError # NOQA else: # https://github.com/PythonCharmers/python-future/blob/exceptions/ # src/future/types/exceptions/pep3151.py import platform def _instance_checking_exception(base_exception=Exception): def wrapped(instance_checker): class TemporaryClass(base_exception): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], TemporaryClass): unwrap_me = args[0] for attr in dir(unwrap_me): if not attr.startswith('__'): setattr(self, attr, getattr(unwrap_me, attr)) else: super(TemporaryClass, self).__init__(*args, **kwargs) class __metaclass__(type): def __instancecheck__(cls, inst): return instance_checker(inst) def __subclasscheck__(cls, classinfo): value = sys.exc_info()[1] return isinstance(value, cls) TemporaryClass.__name__ = instance_checker.__name__ TemporaryClass.__doc__ = instance_checker.__doc__ return TemporaryClass return wrapped def FileNotFoundError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT def ProcessLookupError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH def PermissionError(inst): return getattr(inst, 'errno', _SENTINEL) in ( errno.EACCES, errno.EPERM) def InterruptedError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EINTR def ChildProcessError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD def FileExistsError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST if platform.python_implementation() != "CPython": try: raise OSError(errno.EEXIST, "perm") except FileExistsError: pass except OSError: raise RuntimeError( "broken or incompatible Python implementation, see: " "https://github.com/giampaolo/psutil/issues/1659") The provided code snippet includes necessary dependencies for implementing the `net_if_stats` function. Write a Python function `def net_if_stats()` to solve the following problem: Get NIC stats (isup, duplex, speed, mtu). Here is the function: def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" duplex_map = {"Full": NIC_DUPLEX_FULL, "Half": NIC_DUPLEX_HALF} names = set([x[0] for x in net_if_addrs()]) ret = {} for name in names: mtu = cext_posix.net_if_mtu(name) flags = cext_posix.net_if_flags(name) # try to get speed and duplex # TODO: rewrite this in C (entstat forks, so use truss -f to follow. # looks like it is using an undocumented ioctl?) duplex = "" speed = 0 p = subprocess.Popen(["/usr/bin/entstat", "-d", name], 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: re_result = re.search( r"Running: (\d+) Mbps.*?(\w+) Duplex", stdout) if re_result is not None: speed = int(re_result.group(1)) duplex = re_result.group(2) output_flags = ','.join(flags) isup = 'running' in flags duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN) ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags) return ret
Get NIC stats (isup, duplex, speed, mtu).
176,236
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `boot_time` function. Write a Python function `def boot_time()` to solve the following problem: The system boot time expressed in seconds since the epoch. Here is the function: def boot_time(): """The system boot time expressed in seconds since the epoch.""" return cext.boot_time()
The system boot time expressed in seconds since the epoch.
176,237
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `users` function. Write a Python function `def users()` to solve the following problem: Return currently connected users as a list of namedtuples. Here is the function: def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() localhost = (':0.0', ':0') for item in rawlist: user, tty, hostname, tstamp, user_process, pid = item # note: the underlying C function includes entries about # system boot, run level and others. We might want # to use them in the future. if not user_process: continue if hostname in localhost: hostname = 'localhost' nt = _common.suser(user, tty, hostname, tstamp, pid) retlist.append(nt) return retlist
Return currently connected users as a list of namedtuples.
176,238
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `pids` function. Write a Python function `def pids()` to solve the following problem: Returns a list of PIDs currently running on the system. Here is the function: def pids(): """Returns a list of PIDs currently running on the system.""" return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
Returns a list of PIDs currently running on the system.
176,239
import functools import glob import os import re import subprocess import sys from collections import namedtuple from . import _common from . import _psposix from . import _psutil_aix as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_to_ntuple from ._common import get_procfs_path from ._common import memoize_when_activated from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError def pid_exists(pid): """Check for the existence of a unix pid.""" return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo")) class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class ZombieProcess(NoSuchProcess): """Exception raised when querying a zombie process. This is raised on macOS, BSD and Solaris only, and not always: depending on the query the OS may be able to succeed anyway. On Linux all zombie processes are querable (hence this is never raised). Windows doesn't have zombie processes. """ __module__ = 'psutil' def __init__(self, pid, name=None, ppid=None, msg=None): NoSuchProcess.__init__(self, pid, name, msg) self.ppid = ppid self.msg = msg or "PID still exists but it's a zombie" class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions` function. Write a Python function `def wrap_exceptions(fun)` to solve the following problem: Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. Here is the function: def wrap_exceptions(fun): """Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except (FileNotFoundError, ProcessLookupError): # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) except PermissionError: raise AccessDenied(self.pid, self._name) return wrapper
Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
176,240
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError svmem = namedtuple( 'svmem', ['total', 'available', 'percent', 'used', 'free', 'active', 'inactive', 'wired']) def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `virtual_memory` function. Write a Python function `def virtual_memory()` to solve the following problem: System virtual memory as a namedtuple. Here is the function: def virtual_memory(): """System virtual memory as a namedtuple.""" total, active, inactive, wired, free, speculative = cext.virtual_mem() # This is how Zabbix calculate avail and used mem: # https://github.com/zabbix/zabbix/blob/trunk/src/libs/zbxsysinfo/ # osx/memory.c # Also see: https://github.com/giampaolo/psutil/issues/1277 avail = inactive + free used = active + wired # This is NOT how Zabbix calculates free mem but it matches "free" # cmdline utility. free -= speculative percent = usage_percent((total - avail), total, round_=1) return svmem(total, avail, percent, used, free, active, inactive, wired)
System virtual memory as a namedtuple.
176,241
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `swap_memory` function. Write a Python function `def swap_memory()` to solve the following problem: Swap system memory as a (total, used, free, sin, sout) tuple. Here is the function: def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, used, free, sin, sout = cext.swap_mem() percent = usage_percent(used, total, round_=1) return _common.sswap(total, used, free, percent, sin, sout)
Swap system memory as a (total, used, free, sin, sout) tuple.
176,242
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle']) The provided code snippet includes necessary dependencies for implementing the `cpu_times` function. Write a Python function `def cpu_times()` to solve the following problem: Return system CPU times as a namedtuple. Here is the function: def cpu_times(): """Return system CPU times as a namedtuple.""" user, nice, system, idle = cext.cpu_times() return scputimes(user, nice, system, idle)
Return system CPU times as a namedtuple.
176,243
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle']) The provided code snippet includes necessary dependencies for implementing the `per_cpu_times` function. Write a Python function `def per_cpu_times()` to solve the following problem: Return system CPU times as a named tuple Here is the function: def per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in cext.per_cpu_times(): user, nice, system, idle = cpu_t item = scputimes(user, nice, system, idle) ret.append(item) return ret
Return system CPU times as a named tuple
176,244
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `cpu_count_logical` function. Write a Python function `def cpu_count_logical()` to solve the following problem: Return the number of logical CPUs in the system. Here is the function: def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical()
Return the number of logical CPUs in the system.
176,245
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `cpu_count_cores` function. Write a Python function `def cpu_count_cores()` to solve the following problem: Return the number of CPU cores in the system. Here is the function: def cpu_count_cores(): """Return the number of CPU cores in the system.""" return cext.cpu_count_cores()
Return the number of CPU cores in the system.
176,246
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError def cpu_stats(): ctx_switches, interrupts, soft_interrupts, syscalls, traps = \ cext.cpu_stats() return _common.scpustats( ctx_switches, interrupts, soft_interrupts, syscalls)
null
176,247
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `cpu_freq` function. Write a Python function `def cpu_freq()` to solve the following problem: Return CPU frequency. On macOS per-cpu frequency is not supported. Also, the returned frequency never changes, see: https://arstechnica.com/civis/viewtopic.php?f=19&t=465002 Here is the function: def cpu_freq(): """Return CPU frequency. On macOS per-cpu frequency is not supported. Also, the returned frequency never changes, see: https://arstechnica.com/civis/viewtopic.php?f=19&t=465002 """ curr, min_, max_ = cext.cpu_freq() return [_common.scpufreq(curr, min_, max_)]
Return CPU frequency. On macOS per-cpu frequency is not supported. Also, the returned frequency never changes, see: https://arstechnica.com/civis/viewtopic.php?f=19&t=465002
176,248
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `disk_partitions` function. Write a Python function `def disk_partitions(all=False)` to solve the following problem: Return mounted disk partitions as a list of namedtuples. Here is the function: def disk_partitions(all=False): """Return mounted disk partitions as a list of namedtuples.""" retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: if not os.path.isabs(device) or not os.path.exists(device): continue maxfile = maxpath = None # set later ntuple = _common.sdiskpart(device, mountpoint, fstype, opts, maxfile, maxpath) retlist.append(ntuple) return retlist
Return mounted disk partitions as a list of namedtuples.
176,249
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `sensors_battery` function. Write a Python function `def sensors_battery()` to solve the following problem: Return battery information. Here is the function: def sensors_battery(): """Return battery information.""" try: percent, minsleft, power_plugged = cext.sensors_battery() except NotImplementedError: # no power source - return None according to interface return None power_plugged = power_plugged == 1 if power_plugged: secsleft = _common.POWER_TIME_UNLIMITED elif minsleft == -1: secsleft = _common.POWER_TIME_UNKNOWN else: secsleft = minsleft * 60 return _common.sbattery(percent, secsleft, power_plugged)
Return battery information.
176,250
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError def pids(): ls = cext.pids() if 0 not in ls: # On certain macOS versions pids() C doesn't return PID 0 but # "ps" does and the process is querable via sysctl(): # https://travis-ci.org/giampaolo/psutil/jobs/309619941 try: Process(0).create_time() ls.insert(0, 0) except NoSuchProcess: pass except AccessDenied: ls.insert(0, 0) return ls class Process(object): """Wrapper class around underlying C implementation.""" __slots__ = ["pid", "_name", "_ppid", "_cache"] def __init__(self, pid): self.pid = pid self._name = None self._ppid = None def _get_kinfo_proc(self): # Note: should work with all PIDs without permission issues. ret = cext.proc_kinfo_oneshot(self.pid) assert len(ret) == len(kinfo_proc_map) return ret def _get_pidtaskinfo(self): # Note: should work for PIDs owned by user only. ret = cext.proc_pidtaskinfo_oneshot(self.pid) assert len(ret) == len(pidtaskinfo_map) return ret def oneshot_enter(self): self._get_kinfo_proc.cache_activate(self) self._get_pidtaskinfo.cache_activate(self) def oneshot_exit(self): self._get_kinfo_proc.cache_deactivate(self) self._get_pidtaskinfo.cache_deactivate(self) def name(self): name = self._get_kinfo_proc()[kinfo_proc_map['name']] return name if name is not None else cext.proc_name(self.pid) def exe(self): return cext.proc_exe(self.pid) def cmdline(self): return cext.proc_cmdline(self.pid) def environ(self): return parse_environ_block(cext.proc_environ(self.pid)) def ppid(self): self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']] return self._ppid def cwd(self): return cext.proc_cwd(self.pid) def uids(self): rawtuple = self._get_kinfo_proc() return _common.puids( rawtuple[kinfo_proc_map['ruid']], rawtuple[kinfo_proc_map['euid']], rawtuple[kinfo_proc_map['suid']]) def gids(self): rawtuple = self._get_kinfo_proc() return _common.puids( rawtuple[kinfo_proc_map['rgid']], rawtuple[kinfo_proc_map['egid']], rawtuple[kinfo_proc_map['sgid']]) def terminal(self): tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']] tmap = _psposix.get_terminal_map() try: return tmap[tty_nr] except KeyError: return None def memory_info(self): rawtuple = self._get_pidtaskinfo() return pmem( rawtuple[pidtaskinfo_map['rss']], rawtuple[pidtaskinfo_map['vms']], rawtuple[pidtaskinfo_map['pfaults']], rawtuple[pidtaskinfo_map['pageins']], ) def memory_full_info(self): basic_mem = self.memory_info() uss = cext.proc_memory_uss(self.pid) return pfullmem(*basic_mem + (uss, )) def cpu_times(self): rawtuple = self._get_pidtaskinfo() return _common.pcputimes( rawtuple[pidtaskinfo_map['cpuutime']], rawtuple[pidtaskinfo_map['cpustime']], # children user / system times are not retrievable (set to 0) 0.0, 0.0) def create_time(self): return self._get_kinfo_proc()[kinfo_proc_map['ctime']] def num_ctx_switches(self): # Unvoluntary value seems not to be available; # getrusage() numbers seems to confirm this theory. # We set it to 0. vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']] return _common.pctxsw(vol, 0) def num_threads(self): return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']] def open_files(self): if self.pid == 0: return [] files = [] rawlist = cext.proc_open_files(self.pid) for path, fd in rawlist: if isfile_strict(path): ntuple = _common.popenfile(path, fd) files.append(ntuple) return files def connections(self, kind='inet'): if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.proc_connections(self.pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status = item nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status, TCP_STATUSES) ret.append(nt) return ret def num_fds(self): if self.pid == 0: return 0 return cext.proc_num_fds(self.pid) def wait(self, timeout=None): return _psposix.wait_pid(self.pid, timeout, self._name) def nice_get(self): return cext_posix.getpriority(self.pid) def nice_set(self, value): return cext_posix.setpriority(self.pid, value) def status(self): code = self._get_kinfo_proc()[kinfo_proc_map['status']] # XXX is '?' legit? (we're not supposed to return it anyway) return PROC_STATUSES.get(code, '?') def threads(self): rawlist = cext.proc_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = _common.pthread(thread_id, utime, stime) retlist.append(ntuple) return retlist class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" The provided code snippet includes necessary dependencies for implementing the `net_connections` function. Write a Python function `def net_connections(kind='inet')` to solve the following problem: System-wide network connections. Here is the function: def net_connections(kind='inet'): """System-wide network connections.""" # Note: on macOS this will fail with AccessDenied unless # the process is owned by root. ret = [] for pid in pids(): try: cons = Process(pid).connections(kind) except NoSuchProcess: continue else: if cons: for c in cons: c = list(c) + [pid] ret.append(_common.sconn(*c)) return ret
System-wide network connections.
176,251
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError net_io_counters = cext.net_io_counters The provided code snippet includes necessary dependencies for implementing the `net_if_stats` function. Write a Python function `def net_if_stats()` to solve the following problem: Get NIC stats (isup, duplex, speed, mtu). Here is the function: def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" names = net_io_counters().keys() ret = {} for name in names: try: mtu = cext_posix.net_if_mtu(name) flags = cext_posix.net_if_flags(name) duplex, speed = cext_posix.net_if_duplex_speed(name) except OSError as err: # https://github.com/giampaolo/psutil/issues/1279 if err.errno != errno.ENODEV: raise else: if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) output_flags = ','.join(flags) isup = 'running' in flags ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags) return ret
Get NIC stats (isup, duplex, speed, mtu).
176,252
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `boot_time` function. Write a Python function `def boot_time()` to solve the following problem: The system boot time expressed in seconds since the epoch. Here is the function: def boot_time(): """The system boot time expressed in seconds since the epoch.""" return cext.boot_time()
The system boot time expressed in seconds since the epoch.
176,253
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError The provided code snippet includes necessary dependencies for implementing the `users` function. Write a Python function `def users()` to solve the following problem: Return currently connected users as a list of namedtuples. Here is the function: def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() for item in rawlist: user, tty, hostname, tstamp, pid = item if tty == '~': continue # reboot or shutdown if not tstamp: continue nt = _common.suser(user, tty or None, hostname or None, tstamp, pid) retlist.append(nt) return retlist
Return currently connected users as a list of namedtuples.
176,254
import errno import functools import os from collections import namedtuple from . import _common from . import _psposix from . import _psutil_osx as cext from . import _psutil_posix as cext_posix from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import isfile_strict from ._common import memoize_when_activated from ._common import parse_environ_block from ._common import usage_percent from ._compat import PermissionError from ._compat import ProcessLookupError def is_zombie(pid): try: st = cext.proc_kinfo_oneshot(pid)[kinfo_proc_map['status']] return st == cext.SZOMB except Exception: return False class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class ZombieProcess(NoSuchProcess): """Exception raised when querying a zombie process. This is raised on macOS, BSD and Solaris only, and not always: depending on the query the OS may be able to succeed anyway. On Linux all zombie processes are querable (hence this is never raised). Windows doesn't have zombie processes. """ __module__ = 'psutil' def __init__(self, pid, name=None, ppid=None, msg=None): NoSuchProcess.__init__(self, pid, name, msg) self.ppid = ppid self.msg = msg or "PID still exists but it's a zombie" class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions` function. Write a Python function `def wrap_exceptions(fun)` to solve the following problem: Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. Here is the function: def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except ProcessLookupError: if is_zombie(self.pid): raise ZombieProcess(self.pid, self._name, self._ppid) else: raise NoSuchProcess(self.pid, self._name) except PermissionError: raise AccessDenied(self.pid, self._name) except cext.ZombieProcessError: raise ZombieProcess(self.pid, self._name, self._ppid) return wrapper
Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied.
176,255
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: def path_exists_strict(path): """Same as os.path.exists() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: os.stat(path) except OSError as err: if err.errno in (errno.EPERM, errno.EACCES): raise return False else: return True The provided code snippet includes necessary dependencies for implementing the `readlink` function. Write a Python function `def readlink(path)` to solve the following problem: Wrapper around os.readlink(). Here is the function: def readlink(path): """Wrapper around os.readlink().""" assert isinstance(path, basestring), path path = os.readlink(path) # readlink() might return paths containing null bytes ('\x00') # resulting in "TypeError: must be encoded string without NULL # bytes, not str" errors when the string is passed to other # fs-related functions (os.*, open(), ...). # Apparently everything after '\x00' is garbage (we can have # ' (deleted)', 'new' and possibly others), see: # https://github.com/giampaolo/psutil/issues/717 path = path.split('\x00')[0] # Certain paths have ' (deleted)' appended. Usually this is # bogus as the file actually exists. Even if it doesn't we # don't care. if path.endswith(' (deleted)') and not path_exists_strict(path): path = path[:-10] return path
Wrapper around os.readlink().
176,256
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: The provided code snippet includes necessary dependencies for implementing the `file_flags_to_mode` function. Write a Python function `def file_flags_to_mode(flags)` to solve the following problem: Convert file's open() flags into a readable string. Used by Process.open_files(). Here is the function: def file_flags_to_mode(flags): """Convert file's open() flags into a readable string. Used by Process.open_files(). """ modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'} mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)] if flags & os.O_APPEND: mode = mode.replace('w', 'a', 1) mode = mode.replace('w+', 'r+') # possible values: r, w, a, r+, a+ return mode
Convert file's open() flags into a readable string. Used by Process.open_files().
176,257
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: def prlimit(pid, resource_, limits=None): class StructRlimit(ctypes.Structure): _fields_ = [('rlim_cur', ctypes.c_longlong), ('rlim_max', ctypes.c_longlong)] current = StructRlimit() if limits is None: # get ret = libc.prlimit(pid, resource_, None, ctypes.byref(current)) else: # set new = StructRlimit() new.rlim_cur = limits[0] new.rlim_max = limits[1] ret = libc.prlimit( pid, resource_, ctypes.byref(new), ctypes.byref(current)) if ret != 0: errno = ctypes.get_errno() raise OSError(errno, os.strerror(errno)) return (current.rlim_cur, current.rlim_max)
null
176,258
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring svmem = namedtuple( 'svmem', ['total', 'available', 'percent', 'used', 'free', 'active', 'inactive', 'buffers', 'cached', 'shared', 'slab']) def calculate_avail_vmem(mems): """Fallback for kernels < 3.14 where /proc/meminfo does not provide "MemAvailable:" column, see: https://blog.famzah.net/2014/09/24/ This code reimplements the algorithm outlined here: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/ commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 XXX: on recent kernels this calculation differs by ~1.5% than "MemAvailable:" as it's calculated slightly differently, see: https://gitlab.com/procps-ng/procps/issues/42 https://github.com/famzah/linux-memavailable-procfs/issues/2 It is still way more realistic than doing (free + cached) though. """ # Fallback for very old distros. According to # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/ # commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 # ...long ago "avail" was calculated as (free + cached). # We might fallback in such cases: # "Active(file)" not available: 2.6.28 / Dec 2008 # "Inactive(file)" not available: 2.6.28 / Dec 2008 # "SReclaimable:" not available: 2.6.19 / Nov 2006 # /proc/zoneinfo not available: 2.6.13 / Aug 2005 free = mems[b'MemFree:'] fallback = free + mems.get(b"Cached:", 0) try: lru_active_file = mems[b'Active(file):'] lru_inactive_file = mems[b'Inactive(file):'] slab_reclaimable = mems[b'SReclaimable:'] except KeyError: return fallback try: f = open_binary('%s/zoneinfo' % get_procfs_path()) except IOError: return fallback # kernel 2.6.13 watermark_low = 0 with f: for line in f: line = line.strip() if line.startswith(b'low'): watermark_low += int(line.split()[1]) watermark_low *= PAGESIZE avail = free - watermark_low pagecache = lru_active_file + lru_inactive_file pagecache -= min(pagecache / 2, watermark_low) avail += pagecache avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low) return int(avail) def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `virtual_memory` function. Write a Python function `def virtual_memory()` to solve the following problem: Report virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04. Note about "available" memory: up until psutil 4.3 it was calculated as "avail = (free + buffers + cached)". Now "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as it's more accurate. That matches "available" column in newer versions of "free". Here is the function: def virtual_memory(): """Report virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04. Note about "available" memory: up until psutil 4.3 it was calculated as "avail = (free + buffers + cached)". Now "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as it's more accurate. That matches "available" column in newer versions of "free". """ missing_fields = [] mems = {} with open_binary('%s/meminfo' % get_procfs_path()) as f: for line in f: fields = line.split() mems[fields[0]] = int(fields[1]) * 1024 # /proc doc states that the available fields in /proc/meminfo vary # by architecture and compile options, but these 3 values are also # returned by sysinfo(2); as such we assume they are always there. total = mems[b'MemTotal:'] free = mems[b'MemFree:'] try: buffers = mems[b'Buffers:'] except KeyError: # https://github.com/giampaolo/psutil/issues/1010 buffers = 0 missing_fields.append('buffers') try: cached = mems[b"Cached:"] except KeyError: cached = 0 missing_fields.append('cached') else: # "free" cmdline utility sums reclaimable to cached. # Older versions of procps used to add slab memory instead. # This got changed in: # https://gitlab.com/procps-ng/procps/commit/ # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19 try: shared = mems[b'Shmem:'] # since kernel 2.6.32 except KeyError: try: shared = mems[b'MemShared:'] # kernels 2.4 except KeyError: shared = 0 missing_fields.append('shared') try: active = mems[b"Active:"] except KeyError: active = 0 missing_fields.append('active') try: inactive = mems[b"Inactive:"] except KeyError: try: inactive = \ mems[b"Inact_dirty:"] + \ mems[b"Inact_clean:"] + \ mems[b"Inact_laundry:"] except KeyError: inactive = 0 missing_fields.append('inactive') try: slab = mems[b"Slab:"] except KeyError: slab = 0 used = total - free - cached - buffers if used < 0: # May be symptomatic of running within a LCX container where such # values will be dramatically distorted over those of the host. used = total - free # - starting from 4.4.0 we match free's "available" column. # Before 4.4.0 we calculated it as (free + buffers + cached) # which matched htop. # - free and htop available memory differs as per: # http://askubuntu.com/a/369589 # http://unix.stackexchange.com/a/65852/168884 # - MemAvailable has been introduced in kernel 3.14 try: avail = mems[b'MemAvailable:'] except KeyError: avail = calculate_avail_vmem(mems) if avail < 0: avail = 0 missing_fields.append('available') # If avail is greater than total or our calculation overflows, # that's symptomatic of running within a LCX container where such # values will be dramatically distorted over those of the host. # https://gitlab.com/procps-ng/procps/blob/ # 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764 if avail > total: avail = free percent = usage_percent((total - avail), total, round_=1) # Warn about missing metrics which are set to 0. if missing_fields: msg = "%s memory stats couldn't be determined and %s set to 0" % ( ", ".join(missing_fields), "was" if len(missing_fields) == 1 else "were") warnings.warn(msg, RuntimeWarning) return svmem(total, avail, percent, used, free, active, inactive, buffers, cached, shared, slab)
Report virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04. Note about "available" memory: up until psutil 4.3 it was calculated as "avail = (free + buffers + cached)". Now "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as it's more accurate. That matches "available" column in newer versions of "free".
176,259
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `swap_memory` function. Write a Python function `def swap_memory()` to solve the following problem: Return swap memory metrics. Here is the function: def swap_memory(): """Return swap memory metrics.""" mems = {} with open_binary('%s/meminfo' % get_procfs_path()) as f: for line in f: fields = line.split() mems[fields[0]] = int(fields[1]) * 1024 # We prefer /proc/meminfo over sysinfo() syscall so that # psutil.PROCFS_PATH can be used in order to allow retrieval # for linux containers, see: # https://github.com/giampaolo/psutil/issues/1015 try: total = mems[b'SwapTotal:'] free = mems[b'SwapFree:'] except KeyError: _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo() total *= unit_multiplier free *= unit_multiplier used = total - free percent = usage_percent(used, total, round_=1) # get pgin/pgouts try: f = open_binary("%s/vmstat" % get_procfs_path()) except IOError as err: # see https://github.com/giampaolo/psutil/issues/722 msg = "'sin' and 'sout' swap memory stats couldn't " \ "be determined and were set to 0 (%s)" % str(err) warnings.warn(msg, RuntimeWarning) sin = sout = 0 else: with f: sin = sout = None for line in f: # values are expressed in 4 kilo bytes, we want # bytes instead if line.startswith(b'pswpin'): sin = int(line.split(b' ')[1]) * 4 * 1024 elif line.startswith(b'pswpout'): sout = int(line.split(b' ')[1]) * 4 * 1024 if sin is not None and sout is not None: break else: # we might get here when dealing with exotic Linux # flavors, see: # https://github.com/giampaolo/psutil/issues/313 msg = "'sin' and 'sout' swap memory stats couldn't " \ "be determined and were set to 0" warnings.warn(msg, RuntimeWarning) sin = sout = 0 return _common.sswap(total, used, free, percent, sin, sout)
Return swap memory metrics.
176,260
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring CLOCK_TICKS = os.sysconf("SC_CLK_TCK") def set_scputimes_ntuple(procfs_path): """Set a namedtuple of variable fields depending on the CPU times available on this Linux kernel version which may be: (user, nice, system, idle, iowait, irq, softirq, [steal, [guest, [guest_nice]]]) Used by cpu_times() function. """ global scputimes with open_binary('%s/stat' % procfs_path) as f: values = f.readline().split()[1:] fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq'] vlen = len(values) if vlen >= 8: # Linux >= 2.6.11 fields.append('steal') if vlen >= 9: # Linux >= 2.6.24 fields.append('guest') if vlen >= 10: # Linux >= 3.2.0 fields.append('guest_nice') scputimes = namedtuple('scputimes', fields) try: set_scputimes_ntuple("/proc") except Exception: # pragma: no cover # Don't want to crash at import time. traceback.print_exc() scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0) def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `cpu_times` function. Write a Python function `def cpu_times()` to solve the following problem: Return a named tuple representing the following system-wide CPU times: (user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]) Last 3 fields may not be available on all Linux kernel versions. Here is the function: def cpu_times(): """Return a named tuple representing the following system-wide CPU times: (user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]) Last 3 fields may not be available on all Linux kernel versions. """ procfs_path = get_procfs_path() set_scputimes_ntuple(procfs_path) with open_binary('%s/stat' % procfs_path) as f: values = f.readline().split() fields = values[1:len(scputimes._fields) + 1] fields = [float(x) / CLOCK_TICKS for x in fields] return scputimes(*fields)
Return a named tuple representing the following system-wide CPU times: (user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]) Last 3 fields may not be available on all Linux kernel versions.
176,261
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring CLOCK_TICKS = os.sysconf("SC_CLK_TCK") def set_scputimes_ntuple(procfs_path): """Set a namedtuple of variable fields depending on the CPU times available on this Linux kernel version which may be: (user, nice, system, idle, iowait, irq, softirq, [steal, [guest, [guest_nice]]]) Used by cpu_times() function. """ global scputimes with open_binary('%s/stat' % procfs_path) as f: values = f.readline().split()[1:] fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq'] vlen = len(values) if vlen >= 8: # Linux >= 2.6.11 fields.append('steal') if vlen >= 9: # Linux >= 2.6.24 fields.append('guest') if vlen >= 10: # Linux >= 3.2.0 fields.append('guest_nice') scputimes = namedtuple('scputimes', fields) try: set_scputimes_ntuple("/proc") except Exception: # pragma: no cover # Don't want to crash at import time. traceback.print_exc() scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0) def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `per_cpu_times` function. Write a Python function `def per_cpu_times()` to solve the following problem: Return a list of namedtuple representing the CPU times for every CPU available on the system. Here is the function: def per_cpu_times(): """Return a list of namedtuple representing the CPU times for every CPU available on the system. """ procfs_path = get_procfs_path() set_scputimes_ntuple(procfs_path) cpus = [] with open_binary('%s/stat' % procfs_path) as f: # get rid of the first line which refers to system wide CPU stats f.readline() for line in f: if line.startswith(b'cpu'): values = line.split() fields = values[1:len(scputimes._fields) + 1] fields = [float(x) / CLOCK_TICKS for x in fields] entry = scputimes(*fields) cpus.append(entry) return cpus
Return a list of namedtuple representing the CPU times for every CPU available on the system.
176,262
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def open_text(fname): """On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). """ if not PY3: return open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE) # See: # https://github.com/giampaolo/psutil/issues/675 # https://github.com/giampaolo/psutil/pull/733 fobj = open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE, encoding=ENCODING, errors=ENCODING_ERRS) try: # Dictates per-line read(2) buffer size. Defaults is 8k. See: # https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546 fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE except AttributeError: pass except Exception: fobj.close() raise return fobj def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `cpu_count_logical` function. Write a Python function `def cpu_count_logical()` to solve the following problem: Return the number of logical CPUs in the system. Here is the function: def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: # as a second fallback we try to parse /proc/cpuinfo num = 0 with open_binary('%s/cpuinfo' % get_procfs_path()) as f: for line in f: if line.lower().startswith(b'processor'): num += 1 # unknown format (e.g. amrel/sparc architectures), see: # https://github.com/giampaolo/psutil/issues/200 # try to parse /proc/stat as a last resort if num == 0: search = re.compile(r'cpu\d') with open_text('%s/stat' % get_procfs_path()) as f: for line in f: line = line.split(' ')[0] if search.match(line): num += 1 if num == 0: # mimic os.cpu_count() return None return num
Return the number of logical CPUs in the system.
176,263
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `cpu_count_cores` function. Write a Python function `def cpu_count_cores()` to solve the following problem: Return the number of CPU cores in the system. Here is the function: def cpu_count_cores(): """Return the number of CPU cores in the system.""" # Method #1 ls = set() # These 2 files are the same but */core_cpus_list is newer while # */thread_siblings_list is deprecated and may disappear in the future. # https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst # https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964 # https://lkml.org/lkml/2019/2/26/41 p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list" p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list" for path in glob.glob(p1) or glob.glob(p2): with open_binary(path) as f: ls.add(f.read().strip()) result = len(ls) if result != 0: return result # Method #2 mapping = {} current_info = {} with open_binary('%s/cpuinfo' % get_procfs_path()) as f: for line in f: line = line.strip().lower() if not line: # new section try: mapping[current_info[b'physical id']] = \ current_info[b'cpu cores'] except KeyError: pass current_info = {} else: # ongoing section if line.startswith((b'physical id', b'cpu cores')): key, value = line.split(b'\t:', 1) current_info[key] = int(value) result = sum(mapping.values()) return result or None # mimic os.cpu_count()
Return the number of CPU cores in the system.
176,264
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `cpu_stats` function. Write a Python function `def cpu_stats()` to solve the following problem: Return various CPU stats as a named tuple. Here is the function: def cpu_stats(): """Return various CPU stats as a named tuple.""" with open_binary('%s/stat' % get_procfs_path()) as f: ctx_switches = None interrupts = None soft_interrupts = None for line in f: if line.startswith(b'ctxt'): ctx_switches = int(line.split()[1]) elif line.startswith(b'intr'): interrupts = int(line.split()[1]) elif line.startswith(b'softirq'): soft_interrupts = int(line.split()[1]) if ctx_switches is not None and soft_interrupts is not None \ and interrupts is not None: break syscalls = 0 return _common.scpustats( ctx_switches, interrupts, soft_interrupts, syscalls)
Return various CPU stats as a named tuple.
176,265
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def _cpu_get_cpuinfo_freq(): """Return current CPU frequency from cpuinfo if available. """ ret = [] with open_binary('%s/cpuinfo' % get_procfs_path()) as f: for line in f: if line.lower().startswith(b'cpu mhz'): ret.append(float(line.split(b':', 1)[1])) return ret if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: def bcat(fname, fallback=_DEFAULT): """Same as above but opens file in binary mode.""" return cat(fname, fallback=fallback, _open=open_binary) The provided code snippet includes necessary dependencies for implementing the `cpu_freq` function. Write a Python function `def cpu_freq()` to solve the following problem: Return frequency metrics for all CPUs. Contrarily to other OSes, Linux updates these values in real-time. Here is the function: def cpu_freq(): """Return frequency metrics for all CPUs. Contrarily to other OSes, Linux updates these values in real-time. """ cpuinfo_freqs = _cpu_get_cpuinfo_freq() paths = \ glob.glob("/sys/devices/system/cpu/cpufreq/policy[0-9]*") or \ glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq") paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group())) ret = [] pjoin = os.path.join for i, path in enumerate(paths): if len(paths) == len(cpuinfo_freqs): # take cached value from cpuinfo if available, see: # https://github.com/giampaolo/psutil/issues/1851 curr = cpuinfo_freqs[i] * 1000 else: curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None) if curr is None: # Likely an old RedHat, see: # https://github.com/giampaolo/psutil/issues/1071 curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None) if curr is None: raise NotImplementedError( "can't find current frequency file") curr = int(curr) / 1000 max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000 min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000 ret.append(_common.scpufreq(curr, min_, max_)) return ret
Return frequency metrics for all CPUs. Contrarily to other OSes, Linux updates these values in real-time.
176,266
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def _cpu_get_cpuinfo_freq(): """Return current CPU frequency from cpuinfo if available. """ ret = [] with open_binary('%s/cpuinfo' % get_procfs_path()) as f: for line in f: if line.lower().startswith(b'cpu mhz'): ret.append(float(line.split(b':', 1)[1])) return ret The provided code snippet includes necessary dependencies for implementing the `cpu_freq` function. Write a Python function `def cpu_freq()` to solve the following problem: Alternate implementation using /proc/cpuinfo. min and max frequencies are not available and are set to None. Here is the function: def cpu_freq(): """Alternate implementation using /proc/cpuinfo. min and max frequencies are not available and are set to None. """ return [_common.scpufreq(x, 0., 0.) for x in _cpu_get_cpuinfo_freq()]
Alternate implementation using /proc/cpuinfo. min and max frequencies are not available and are set to None.
176,267
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring _connections = Connections() The provided code snippet includes necessary dependencies for implementing the `net_connections` function. Write a Python function `def net_connections(kind='inet')` to solve the following problem: Return system-wide open connections. Here is the function: def net_connections(kind='inet'): """Return system-wide open connections.""" return _connections.retrieve(kind)
Return system-wide open connections.
176,268
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def net_io_counters(): """Return network I/O statistics for every network interface installed on the system as a dict of raw tuples. """ with open_text("%s/net/dev" % get_procfs_path()) as f: lines = f.readlines() retdict = {} for line in lines[2:]: colon = line.rfind(':') assert colon > 0, repr(line) name = line[:colon].strip() fields = line[colon + 1:].strip().split() # in (bytes_recv, packets_recv, errin, dropin, fifoin, # unused framein, # unused compressedin, # unused multicastin, # unused # out bytes_sent, packets_sent, errout, dropout, fifoout, # unused collisionsout, # unused carrierout, # unused compressedout) = map(int, fields) retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout) return retdict def debug(msg): """If PSUTIL_DEBUG env var is set, print a debug message to stderr.""" if PSUTIL_DEBUG: import inspect fname, lineno, func_name, lines, index = inspect.getframeinfo( inspect.currentframe().f_back) if isinstance(msg, Exception): if isinstance(msg, (OSError, IOError, EnvironmentError)): # ...because str(exc) may contain info about the file name msg = "ignoring %s" % msg else: msg = "ignoring %r" % msg print("psutil-debug [%s:%s]> %s" % (fname, lineno, msg), # NOQA file=sys.stderr) The provided code snippet includes necessary dependencies for implementing the `net_if_stats` function. Write a Python function `def net_if_stats()` to solve the following problem: Get NIC stats (isup, duplex, speed, mtu). Here is the function: def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" duplex_map = {cext.DUPLEX_FULL: NIC_DUPLEX_FULL, cext.DUPLEX_HALF: NIC_DUPLEX_HALF, cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN} names = net_io_counters().keys() ret = {} for name in names: try: mtu = cext_posix.net_if_mtu(name) flags = cext_posix.net_if_flags(name) duplex, speed = cext.net_if_duplex_speed(name) except OSError as err: # https://github.com/giampaolo/psutil/issues/1279 if err.errno != errno.ENODEV: raise else: debug(err) else: output_flags = ','.join(flags) isup = 'running' in flags ret[name] = _common.snicstats(isup, duplex_map[duplex], speed, mtu, output_flags) return ret
Get NIC stats (isup, duplex, speed, mtu).
176,269
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring DISK_SECTOR_SIZE = 512 def is_storage_device(name): """Return True if the given name refers to a root device (e.g. "sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1", "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram") return True. """ # Re-adapted from iostat source code, see: # https://github.com/sysstat/sysstat/blob/ # 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208 # Some devices may have a slash in their name (e.g. cciss/c0d0...). name = name.replace('/', '!') including_virtual = True if including_virtual: path = "/sys/block/%s" % name else: path = "/sys/block/%s/device" % name return os.access(path, os.F_OK) if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: def open_text(fname): """On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). """ if not PY3: return open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE) # See: # https://github.com/giampaolo/psutil/issues/675 # https://github.com/giampaolo/psutil/pull/733 fobj = open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE, encoding=ENCODING, errors=ENCODING_ERRS) try: # Dictates per-line read(2) buffer size. Defaults is 8k. See: # https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546 fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE except AttributeError: pass except Exception: fobj.close() raise return fobj def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `disk_io_counters` function. Write a Python function `def disk_io_counters(perdisk=False)` to solve the following problem: Return disk I/O statistics for every disk installed on the system as a dict of raw tuples. Here is the function: def disk_io_counters(perdisk=False): """Return disk I/O statistics for every disk installed on the system as a dict of raw tuples. """ def read_procfs(): # OK, this is a bit confusing. The format of /proc/diskstats can # have 3 variations. # On Linux 2.4 each line has always 15 fields, e.g.: # "3 0 8 hda 8 8 8 8 8 8 8 8 8 8 8" # On Linux 2.6+ each line *usually* has 14 fields, and the disk # name is in another position, like this: # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8" # ...unless (Linux 2.6) the line refers to a partition instead # of a disk, in which case the line has less fields (7): # "3 1 hda1 8 8 8 8" # 4.18+ has 4 fields added: # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0" # 5.5 has 2 more fields. # See: # https://www.kernel.org/doc/Documentation/iostats.txt # https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats with open_text("%s/diskstats" % get_procfs_path()) as f: lines = f.readlines() for line in lines: fields = line.split() flen = len(fields) if flen == 15: # Linux 2.4 name = fields[3] reads = int(fields[2]) (reads_merged, rbytes, rtime, writes, writes_merged, wbytes, wtime, _, busy_time, _) = map(int, fields[4:14]) elif flen == 14 or flen >= 18: # Linux 2.6+, line referring to a disk name = fields[2] (reads, reads_merged, rbytes, rtime, writes, writes_merged, wbytes, wtime, _, busy_time, _) = map(int, fields[3:14]) elif flen == 7: # Linux 2.6+, line referring to a partition name = fields[2] reads, rbytes, writes, wbytes = map(int, fields[3:]) rtime = wtime = reads_merged = writes_merged = busy_time = 0 else: raise ValueError("not sure how to interpret line %r" % line) yield (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged, writes_merged, busy_time) def read_sysfs(): for block in os.listdir('/sys/block'): for root, _, files in os.walk(os.path.join('/sys/block', block)): if 'stat' not in files: continue with open_text(os.path.join(root, 'stat')) as f: fields = f.read().strip().split() name = os.path.basename(root) (reads, reads_merged, rbytes, rtime, writes, writes_merged, wbytes, wtime, _, busy_time) = map(int, fields[:10]) yield (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged, writes_merged, busy_time) if os.path.exists('%s/diskstats' % get_procfs_path()): gen = read_procfs() elif os.path.exists('/sys/block'): gen = read_sysfs() else: raise NotImplementedError( "%s/diskstats nor /sys/block filesystem are available on this " "system" % get_procfs_path()) retdict = {} for entry in gen: (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged, writes_merged, busy_time) = entry if not perdisk and not is_storage_device(name): # perdisk=False means we want to calculate totals so we skip # partitions (e.g. 'sda1', 'nvme0n1p1') and only include # base disk devices (e.g. 'sda', 'nvme0n1'). Base disks # include a total of all their partitions + some extra size # of their own: # $ cat /proc/diskstats # 259 0 sda 10485760 ... # 259 1 sda1 5186039 ... # 259 1 sda2 5082039 ... # See: # https://github.com/giampaolo/psutil/pull/1313 continue rbytes *= DISK_SECTOR_SIZE wbytes *= DISK_SECTOR_SIZE retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime, reads_merged, writes_merged, busy_time) return retdict
Return disk I/O statistics for every disk installed on the system as a dict of raw tuples.
176,270
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: class RootFsDeviceFinder: """disk_partitions() may return partitions with device == "/dev/root" or "rootfs". This container class uses different strategies to try to obtain the real device path. Resources: https://bootlin.com/blog/find-root-device/ https://www.systutorials.com/how-to-find-the-disk-where-root-is-on-in-bash-on-linux/ """ __slots__ = ['major', 'minor'] def __init__(self): dev = os.stat("/").st_dev self.major = os.major(dev) self.minor = os.minor(dev) def ask_proc_partitions(self): with open_text("%s/partitions" % get_procfs_path()) as f: for line in f.readlines()[2:]: fields = line.split() if len(fields) < 4: # just for extra safety continue major = int(fields[0]) if fields[0].isdigit() else None minor = int(fields[1]) if fields[1].isdigit() else None name = fields[3] if major == self.major and minor == self.minor: if name: # just for extra safety return "/dev/%s" % name def ask_sys_dev_block(self): path = "/sys/dev/block/%s:%s/uevent" % (self.major, self.minor) with open_text(path) as f: for line in f: if line.startswith("DEVNAME="): name = line.strip().rpartition("DEVNAME=")[2] if name: # just for extra safety return "/dev/%s" % name def ask_sys_class_block(self): needle = "%s:%s" % (self.major, self.minor) files = glob.iglob("/sys/class/block/*/dev") for file in files: try: f = open_text(file) except FileNotFoundError: # race condition continue else: with f: data = f.read().strip() if data == needle: name = os.path.basename(os.path.dirname(file)) return "/dev/%s" % name def find(self): path = None if path is None: try: path = self.ask_proc_partitions() except (IOError, OSError) as err: debug(err) if path is None: try: path = self.ask_sys_dev_block() except (IOError, OSError) as err: debug(err) if path is None: try: path = self.ask_sys_class_block() except (IOError, OSError) as err: debug(err) # We use exists() because the "/dev/*" part of the path is hard # coded, so we want to be sure. if path is not None and os.path.exists(path): return path def open_text(fname): """On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). """ if not PY3: return open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE) # See: # https://github.com/giampaolo/psutil/issues/675 # https://github.com/giampaolo/psutil/pull/733 fobj = open(fname, "rt", buffering=FILE_READ_BUFFER_SIZE, encoding=ENCODING, errors=ENCODING_ERRS) try: # Dictates per-line read(2) buffer size. Defaults is 8k. See: # https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546 fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE except AttributeError: pass except Exception: fobj.close() raise return fobj def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `disk_partitions` function. Write a Python function `def disk_partitions(all=False)` to solve the following problem: Return mounted disk partitions as a list of namedtuples. Here is the function: def disk_partitions(all=False): """Return mounted disk partitions as a list of namedtuples.""" fstypes = set() procfs_path = get_procfs_path() with open_text("%s/filesystems" % procfs_path) as f: for line in f: line = line.strip() if not line.startswith("nodev"): fstypes.add(line.strip()) else: # ignore all lines starting with "nodev" except "nodev zfs" fstype = line.split("\t")[1] if fstype == "zfs": fstypes.add("zfs") # See: https://github.com/giampaolo/psutil/issues/1307 if procfs_path == "/proc" and os.path.isfile('/etc/mtab'): mounts_path = os.path.realpath("/etc/mtab") else: mounts_path = os.path.realpath("%s/self/mounts" % procfs_path) retlist = [] partitions = cext.disk_partitions(mounts_path) for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if device in ("/dev/root", "rootfs"): device = RootFsDeviceFinder().find() or device if not all: if device == '' or fstype not in fstypes: continue maxfile = maxpath = None # set later ntuple = _common.sdiskpart(device, mountpoint, fstype, opts, maxfile, maxpath) retlist.append(ntuple) return retlist
Return mounted disk partitions as a list of namedtuples.
176,271
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] def __init__(self, **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... def __init__( self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT ) -> None: ... def __missing__(self, key: _KT) -> _VT: ... def copy(self: _S) -> _S: ... def cat(fname, fallback=_DEFAULT, _open=open_text): """Read entire file content and return it as a string. File is opened in text mode. If specified, `fallback` is the value returned in case of error, either if the file does not exist or it can't be read(). """ if fallback is _DEFAULT: with _open(fname) as f: return f.read() else: try: with _open(fname) as f: return f.read() except (IOError, OSError): return fallback def bcat(fname, fallback=_DEFAULT): """Same as above but opens file in binary mode.""" return cat(fname, fallback=fallback, _open=open_binary) def debug(msg): """If PSUTIL_DEBUG env var is set, print a debug message to stderr.""" if PSUTIL_DEBUG: import inspect fname, lineno, func_name, lines, index = inspect.getframeinfo( inspect.currentframe().f_back) if isinstance(msg, Exception): if isinstance(msg, (OSError, IOError, EnvironmentError)): # ...because str(exc) may contain info about the file name msg = "ignoring %s" % msg else: msg = "ignoring %r" % msg print("psutil-debug [%s:%s]> %s" % (fname, lineno, msg), # NOQA file=sys.stderr) The provided code snippet includes necessary dependencies for implementing the `sensors_temperatures` function. Write a Python function `def sensors_temperatures()` to solve the following problem: Return hardware (CPU and others) temperatures as a dict including hardware name, label, current, max and critical temperatures. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon - /sys/class/thermal/thermal_zone* is another one but it's more difficult to parse Here is the function: def sensors_temperatures(): """Return hardware (CPU and others) temperatures as a dict including hardware name, label, current, max and critical temperatures. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon - /sys/class/thermal/thermal_zone* is another one but it's more difficult to parse """ ret = collections.defaultdict(list) basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*') # CentOS has an intermediate /device directory: # https://github.com/giampaolo/psutil/issues/971 # https://github.com/nicolargo/glances/issues/1060 basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*')) basenames = sorted(set([x.split('_')[0] for x in basenames])) # Only add the coretemp hwmon entries if they're not already in # /sys/class/hwmon/ # https://github.com/giampaolo/psutil/issues/1708 # https://github.com/giampaolo/psutil/pull/1648 basenames2 = glob.glob( '/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*') repl = re.compile('/sys/devices/platform/coretemp.*/hwmon/') for name in basenames2: altname = repl.sub('/sys/class/hwmon/', name) if altname not in basenames: basenames.append(name) for base in basenames: try: path = base + '_input' current = float(bcat(path)) / 1000.0 path = os.path.join(os.path.dirname(base), 'name') unit_name = cat(path).strip() except (IOError, OSError, ValueError): # A lot of things can go wrong here, so let's just skip the # whole entry. Sure thing is Linux's /sys/class/hwmon really # is a stinky broken mess. # https://github.com/giampaolo/psutil/issues/1009 # https://github.com/giampaolo/psutil/issues/1101 # https://github.com/giampaolo/psutil/issues/1129 # https://github.com/giampaolo/psutil/issues/1245 # https://github.com/giampaolo/psutil/issues/1323 continue high = bcat(base + '_max', fallback=None) critical = bcat(base + '_crit', fallback=None) label = cat(base + '_label', fallback='').strip() if high is not None: try: high = float(high) / 1000.0 except ValueError: high = None if critical is not None: try: critical = float(critical) / 1000.0 except ValueError: critical = None ret[unit_name].append((label, current, high, critical)) # Indication that no sensors were detected in /sys/class/hwmon/ if not basenames: basenames = glob.glob('/sys/class/thermal/thermal_zone*') basenames = sorted(set(basenames)) for base in basenames: try: path = os.path.join(base, 'temp') current = float(bcat(path)) / 1000.0 path = os.path.join(base, 'type') unit_name = cat(path).strip() except (IOError, OSError, ValueError) as err: debug(err) continue trip_paths = glob.glob(base + '/trip_point*') trip_points = set(['_'.join( os.path.basename(p).split('_')[0:3]) for p in trip_paths]) critical = None high = None for trip_point in trip_points: path = os.path.join(base, trip_point + "_type") trip_type = cat(path, fallback='').strip() if trip_type == 'critical': critical = bcat(os.path.join(base, trip_point + "_temp"), fallback=None) elif trip_type == 'high': high = bcat(os.path.join(base, trip_point + "_temp"), fallback=None) if high is not None: try: high = float(high) / 1000.0 except ValueError: high = None if critical is not None: try: critical = float(critical) / 1000.0 except ValueError: critical = None ret[unit_name].append(('', current, high, critical)) return dict(ret)
Return hardware (CPU and others) temperatures as a dict including hardware name, label, current, max and critical temperatures. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon - /sys/class/thermal/thermal_zone* is another one but it's more difficult to parse
176,272
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] def __init__(self, **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... def __init__( self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT ) -> None: ... def __missing__(self, key: _KT) -> _VT: ... def copy(self: _S) -> _S: ... def cat(fname, fallback=_DEFAULT, _open=open_text): """Read entire file content and return it as a string. File is opened in text mode. If specified, `fallback` is the value returned in case of error, either if the file does not exist or it can't be read(). """ if fallback is _DEFAULT: with _open(fname) as f: return f.read() else: try: with _open(fname) as f: return f.read() except (IOError, OSError): return fallback def bcat(fname, fallback=_DEFAULT): """Same as above but opens file in binary mode.""" return cat(fname, fallback=fallback, _open=open_binary) def debug(msg): """If PSUTIL_DEBUG env var is set, print a debug message to stderr.""" if PSUTIL_DEBUG: import inspect fname, lineno, func_name, lines, index = inspect.getframeinfo( inspect.currentframe().f_back) if isinstance(msg, Exception): if isinstance(msg, (OSError, IOError, EnvironmentError)): # ...because str(exc) may contain info about the file name msg = "ignoring %s" % msg else: msg = "ignoring %r" % msg print("psutil-debug [%s:%s]> %s" % (fname, lineno, msg), # NOQA file=sys.stderr) The provided code snippet includes necessary dependencies for implementing the `sensors_fans` function. Write a Python function `def sensors_fans()` to solve the following problem: Return hardware fans info (for CPU and other peripherals) as a dict including hardware label and current speed. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon Here is the function: def sensors_fans(): """Return hardware fans info (for CPU and other peripherals) as a dict including hardware label and current speed. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon """ ret = collections.defaultdict(list) basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*') if not basenames: # CentOS has an intermediate /device directory: # https://github.com/giampaolo/psutil/issues/971 basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*') basenames = sorted(set([x.split('_')[0] for x in basenames])) for base in basenames: try: current = int(bcat(base + '_input')) except (IOError, OSError) as err: debug(err) continue unit_name = cat(os.path.join(os.path.dirname(base), 'name')).strip() label = cat(base + '_label', fallback='').strip() ret[unit_name].append(_common.sfan(label, current)) return dict(ret)
Return hardware fans info (for CPU and other peripherals) as a dict including hardware label and current speed. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
176,273
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring POWER_SUPPLY_PATH = "/sys/class/power_supply" if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: def cat(fname, fallback=_DEFAULT, _open=open_text): """Read entire file content and return it as a string. File is opened in text mode. If specified, `fallback` is the value returned in case of error, either if the file does not exist or it can't be read(). """ if fallback is _DEFAULT: with _open(fname) as f: return f.read() else: try: with _open(fname) as f: return f.read() except (IOError, OSError): return fallback def bcat(fname, fallback=_DEFAULT): """Same as above but opens file in binary mode.""" return cat(fname, fallback=fallback, _open=open_binary) The provided code snippet includes necessary dependencies for implementing the `sensors_battery` function. Write a Python function `def sensors_battery()` to solve the following problem: Return battery information. Implementation note: it appears /sys/class/power_supply/BAT0/ directory structure may vary and provide files with the same meaning but under different names, see: https://github.com/giampaolo/psutil/issues/966 Here is the function: def sensors_battery(): """Return battery information. Implementation note: it appears /sys/class/power_supply/BAT0/ directory structure may vary and provide files with the same meaning but under different names, see: https://github.com/giampaolo/psutil/issues/966 """ null = object() def multi_bcat(*paths): """Attempt to read the content of multiple files which may not exist. If none of them exist return None. """ for path in paths: ret = bcat(path, fallback=null) if ret != null: try: return int(ret) except ValueError: return ret.strip() return None bats = [x for x in os.listdir(POWER_SUPPLY_PATH) if x.startswith('BAT') or 'battery' in x.lower()] if not bats: return None # Get the first available battery. Usually this is "BAT0", except # some rare exceptions: # https://github.com/giampaolo/psutil/issues/1238 root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0]) # Base metrics. energy_now = multi_bcat( root + "/energy_now", root + "/charge_now") power_now = multi_bcat( root + "/power_now", root + "/current_now") energy_full = multi_bcat( root + "/energy_full", root + "/charge_full") time_to_empty = multi_bcat(root + "/time_to_empty_now") # Percent. If we have energy_full the percentage will be more # accurate compared to reading /capacity file (float vs. int). if energy_full is not None and energy_now is not None: try: percent = 100.0 * energy_now / energy_full except ZeroDivisionError: percent = 0.0 else: percent = int(cat(root + "/capacity", fallback=-1)) if percent == -1: return None # Is AC power cable plugged in? # Note: AC0 is not always available and sometimes (e.g. CentOS7) # it's called "AC". power_plugged = None online = multi_bcat( os.path.join(POWER_SUPPLY_PATH, "AC0/online"), os.path.join(POWER_SUPPLY_PATH, "AC/online")) if online is not None: power_plugged = online == 1 else: status = cat(root + "/status", fallback="").strip().lower() if status == "discharging": power_plugged = False elif status in ("charging", "full"): power_plugged = True # Seconds left. # Note to self: we may also calculate the charging ETA as per: # https://github.com/thialfihar/dotfiles/blob/ # 013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55 if power_plugged: secsleft = _common.POWER_TIME_UNLIMITED elif energy_now is not None and power_now is not None: try: secsleft = int(energy_now / power_now * 3600) except ZeroDivisionError: secsleft = _common.POWER_TIME_UNKNOWN elif time_to_empty is not None: secsleft = int(time_to_empty * 60) if secsleft < 0: secsleft = _common.POWER_TIME_UNKNOWN else: secsleft = _common.POWER_TIME_UNKNOWN return _common.sbattery(percent, secsleft, power_plugged)
Return battery information. Implementation note: it appears /sys/class/power_supply/BAT0/ directory structure may vary and provide files with the same meaning but under different names, see: https://github.com/giampaolo/psutil/issues/966
176,274
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring The provided code snippet includes necessary dependencies for implementing the `users` function. Write a Python function `def users()` to solve the following problem: Return currently connected users as a list of namedtuples. Here is the function: def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() for item in rawlist: user, tty, hostname, tstamp, user_process, pid = item # note: the underlying C function includes entries about # system boot, run level and others. We might want # to use them in the future. if not user_process: continue if hostname in (':0.0', ':0'): hostname = 'localhost' nt = _common.suser(user, tty or None, hostname, tstamp, pid) retlist.append(nt) return retlist
Return currently connected users as a list of namedtuples.
176,275
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring BOOT_TIME = None def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `boot_time` function. Write a Python function `def boot_time()` to solve the following problem: Return the system boot time expressed in seconds since the epoch. Here is the function: def boot_time(): """Return the system boot time expressed in seconds since the epoch.""" global BOOT_TIME path = '%s/stat' % get_procfs_path() with open_binary(path) as f: for line in f: if line.startswith(b'btime'): ret = float(line.strip().split()[1]) BOOT_TIME = ret return ret raise RuntimeError( "line 'btime' not found in %s" % path)
Return the system boot time expressed in seconds since the epoch.
176,276
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def pids(): """Returns a list of PIDs currently running on the system.""" return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()] def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `pid_exists` function. Write a Python function `def pid_exists(pid)` to solve the following problem: Check for the existence of a unix PID. Linux TIDs are not supported (always return False). Here is the function: def pid_exists(pid): """Check for the existence of a unix PID. Linux TIDs are not supported (always return False). """ if not _psposix.pid_exists(pid): return False else: # Linux's apparently does not distinguish between PIDs and TIDs # (thread IDs). # listdir("/proc") won't show any TID (only PIDs) but # os.stat("/proc/{tid}") will succeed if {tid} exists. # os.kill() can also be passed a TID. This is quite confusing. # In here we want to enforce this distinction and support PIDs # only, see: # https://github.com/giampaolo/psutil/issues/687 try: # Note: already checked that this is faster than using a # regular expr. Also (a lot) faster than doing # 'return pid in pids()' path = "%s/%s/status" % (get_procfs_path(), pid) with open_binary(path) as f: for line in f: if line.startswith(b"Tgid:"): tgid = int(line.split()[1]) # If tgid and pid are the same then we're # dealing with a process PID. return tgid == pid raise ValueError("'Tgid' line not found in %s" % path) except (EnvironmentError, ValueError): return pid in pids()
Check for the existence of a unix PID. Linux TIDs are not supported (always return False).
176,277
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring def pids(): """Returns a list of PIDs currently running on the system.""" return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()] def open_binary(fname): return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH The provided code snippet includes necessary dependencies for implementing the `ppid_map` function. Write a Python function `def ppid_map()` to solve the following problem: Obtain a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). Here is the function: def ppid_map(): """Obtain a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). """ ret = {} procfs_path = get_procfs_path() for pid in pids(): try: with open_binary("%s/%s/stat" % (procfs_path, pid)) as f: data = f.read() except (FileNotFoundError, ProcessLookupError): # Note: we should be able to access /stat for all processes # aka it's unlikely we'll bump into EPERM, which is good. pass else: rpar = data.rfind(b')') dset = data[rpar + 2:].split() ppid = int(dset[1]) ret[pid] = ppid return ret
Obtain a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children().
176,278
from __future__ import division import base64 import collections import errno import functools import glob import os import re import socket import struct import sys import traceback import warnings from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_linux as cext from . import _psutil_posix as cext_posix from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import bcat from ._common import cat from ._common import debug from ._common import decode from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize from ._common import memoize_when_activated from ._common import open_binary from ._common import open_text from ._common import parse_environ_block from ._common import path_exists_strict from ._common import supports_ipv6 from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b from ._compat import basestring if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \ os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"): else: class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions` function. Write a Python function `def wrap_exceptions(fun)` to solve the following problem: Decorator which translates bare OSError and IOError exceptions into NoSuchProcess and AccessDenied. Here is the function: def wrap_exceptions(fun): """Decorator which translates bare OSError and IOError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except PermissionError: raise AccessDenied(self.pid, self._name) except ProcessLookupError: raise NoSuchProcess(self.pid, self._name) except FileNotFoundError: if not os.path.exists("%s/%s" % (self._procfs_path, self.pid)): raise NoSuchProcess(self.pid, self._name) # Note: zombies will keep existing under /proc until they're # gone so there's no way to distinguish them in here. raise return wrapper
Decorator which translates bare OSError and IOError exceptions into NoSuchProcess and AccessDenied.
176,279
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM The provided code snippet includes necessary dependencies for implementing the `memoize` function. Write a Python function `def memoize(fun)` to solve the following problem: A simple memoize decorator for functions supporting (hashable) positional arguments. It also provides a cache_clear() function for clearing the cache: >>> @memoize ... def foo() ... return 1 ... >>> foo() 1 >>> foo.cache_clear() >>> Here is the function: def memoize(fun): """A simple memoize decorator for functions supporting (hashable) positional arguments. It also provides a cache_clear() function for clearing the cache: >>> @memoize ... def foo() ... return 1 ... >>> foo() 1 >>> foo.cache_clear() >>> """ @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: ret = cache[key] = fun(*args, **kwargs) return ret def cache_clear(): """Clear cache.""" cache.clear() cache = {} wrapper.cache_clear = cache_clear return wrapper
A simple memoize decorator for functions supporting (hashable) positional arguments. It also provides a cache_clear() function for clearing the cache: >>> @memoize ... def foo() ... return 1 ... >>> foo() 1 >>> foo.cache_clear() >>>
176,280
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM The provided code snippet includes necessary dependencies for implementing the `memoize_when_activated` function. Write a Python function `def memoize_when_activated(fun)` to solve the following problem: A memoize decorator which is disabled by default. It can be activated and deactivated on request. For efficiency reasons it can be used only against class methods accepting no arguments. >>> class Foo: ... @memoize ... def foo() ... print(1) ... >>> f = Foo() >>> # deactivated (default) >>> foo() 1 >>> foo() 1 >>> >>> # activated >>> foo.cache_activate(self) >>> foo() 1 >>> foo() >>> foo() >>> Here is the function: def memoize_when_activated(fun): """A memoize decorator which is disabled by default. It can be activated and deactivated on request. For efficiency reasons it can be used only against class methods accepting no arguments. >>> class Foo: ... @memoize ... def foo() ... print(1) ... >>> f = Foo() >>> # deactivated (default) >>> foo() 1 >>> foo() 1 >>> >>> # activated >>> foo.cache_activate(self) >>> foo() 1 >>> foo() >>> foo() >>> """ @functools.wraps(fun) def wrapper(self): try: # case 1: we previously entered oneshot() ctx ret = self._cache[fun] except AttributeError: # case 2: we never entered oneshot() ctx return fun(self) except KeyError: # case 3: we entered oneshot() ctx but there's no cache # for this entry yet ret = fun(self) try: self._cache[fun] = ret except AttributeError: # multi-threading race condition, see: # https://github.com/giampaolo/psutil/issues/1948 pass return ret def cache_activate(proc): """Activate cache. Expects a Process instance. Cache will be stored as a "_cache" instance attribute.""" proc._cache = {} def cache_deactivate(proc): """Deactivate and clear cache.""" try: del proc._cache except AttributeError: pass wrapper.cache_activate = cache_activate wrapper.cache_deactivate = cache_deactivate return wrapper
A memoize decorator which is disabled by default. It can be activated and deactivated on request. For efficiency reasons it can be used only against class methods accepting no arguments. >>> class Foo: ... @memoize ... def foo() ... print(1) ... >>> f = Foo() >>> # deactivated (default) >>> foo() 1 >>> foo() 1 >>> >>> # activated >>> foo.cache_activate(self) >>> foo() 1 >>> foo() >>> foo() >>>
176,281
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM The provided code snippet includes necessary dependencies for implementing the `isfile_strict` function. Write a Python function `def isfile_strict(path)` to solve the following problem: Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html Here is the function: def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError as err: if err.errno in (errno.EPERM, errno.EACCES): raise return False else: return stat.S_ISREG(st.st_mode)
Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html
176,282
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM try: from socket import AF_INET6 except ImportError: AF_INET6 = None try: from socket import AF_UNIX except ImportError: AF_UNIX = None if AF_INET6 is not None: conn_tmap.update({ "tcp6": ([AF_INET6], [SOCK_STREAM]), "udp6": ([AF_INET6], [SOCK_DGRAM]), }) AF_INET6: AddressFamily SOCK_STREAM: SocketKind The provided code snippet includes necessary dependencies for implementing the `supports_ipv6` function. Write a Python function `def supports_ipv6()` to solve the following problem: Return True if IPv6 is supported on this platform. Here is the function: def supports_ipv6(): """Return True if IPv6 is supported on this platform.""" if not socket.has_ipv6 or AF_INET6 is None: return False try: sock = socket.socket(AF_INET6, socket.SOCK_STREAM) with contextlib.closing(sock): sock.bind(("::1", 0)) return True except socket.error: return False
Return True if IPv6 is supported on this platform.
176,283
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM WINDOWS = os.name == "nt" The provided code snippet includes necessary dependencies for implementing the `parse_environ_block` function. Write a Python function `def parse_environ_block(data)` to solve the following problem: Parse a C environ block of environment variables into a dictionary. Here is the function: def parse_environ_block(data): """Parse a C environ block of environment variables into a dictionary.""" # The block is usually raw data from the target process. It might contain # trailing garbage and lines that do not look like assignments. ret = {} pos = 0 # localize global variable to speed up access. WINDOWS_ = WINDOWS while True: next_pos = data.find("\0", pos) # nul byte at the beginning or double nul byte means finish if next_pos <= pos: break # there might not be an equals sign equal_pos = data.find("=", pos, next_pos) if equal_pos > pos: key = data[pos:equal_pos] value = data[equal_pos + 1:next_pos] # Windows expects environment variables to be uppercase only if WINDOWS_: key = key.upper() ret[key] = value pos = next_pos + 1 return ret
Parse a C environ block of environment variables into a dictionary.
176,284
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM The provided code snippet includes necessary dependencies for implementing the `deprecated_method` function. Write a Python function `def deprecated_method(replacement)` to solve the following problem: A decorator which can be used to mark a method as deprecated 'replcement' is the method name which will be called instead. Here is the function: def deprecated_method(replacement): """A decorator which can be used to mark a method as deprecated 'replcement' is the method name which will be called instead. """ def outer(fun): msg = "%s() is deprecated and will be removed; use %s() instead" % ( fun.__name__, replacement) if fun.__doc__ is None: fun.__doc__ = msg @functools.wraps(fun) def inner(self, *args, **kwargs): warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return getattr(self, replacement)(*args, **kwargs) return inner return outer
A decorator which can be used to mark a method as deprecated 'replcement' is the method name which will be called instead.
176,285
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM _wn = _WrapNumbers() The provided code snippet includes necessary dependencies for implementing the `wrap_numbers` function. Write a Python function `def wrap_numbers(input_dict, name)` to solve the following problem: Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict. Here is the function: def wrap_numbers(input_dict, name): """Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict. """ with _wn.lock: return _wn.run(input_dict, name)
Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict.
176,286
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM The provided code snippet includes necessary dependencies for implementing the `bytes2human` function. Write a Python function `def bytes2human(n, format="%(value).1f%(symbol)s")` to solve the following problem: Used by various scripts. See: http://goo.gl/zeJZl >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' Here is the function: def bytes2human(n, format="%(value).1f%(symbol)s"): """Used by various scripts. See: http://goo.gl/zeJZl >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 for symbol in reversed(symbols[1:]): if n >= prefix[symbol]: value = float(n) / prefix[symbol] return format % locals() return format % dict(symbol=symbols[0], value=n)
Used by various scripts. See: http://goo.gl/zeJZl >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M'
176,287
from __future__ import division from __future__ import print_function import collections import contextlib import errno import functools import os import socket import stat import sys import threading import warnings from collections import namedtuple from socket import AF_INET from socket import SOCK_DGRAM from socket import SOCK_STREAM if sys.version_info >= (3, 4): import enum else: enum = None POSIX = os.name == "posix" def term_supports_colors(file=sys.stdout): # pragma: no cover if os.name == 'nt': return True try: import curses assert file.isatty() curses.setupterm() assert curses.tigetnum("colors") > 0 except Exception: return False else: return True def hilite(s, color=None, bold=False): # pragma: no cover """Return an highlighted version of 'string'.""" if not term_supports_colors(): return s attr = [] colors = dict(green='32', red='91', brown='33', yellow='93', blue='34', violet='35', lightblue='36', grey='37', darkgrey='30') colors[None] = '29' try: color = colors[color] except KeyError: raise ValueError("invalid color %r; choose between %s" % ( list(colors.keys()))) attr.append(color) if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s) import sys if sys.version_info[0] < 3: del num, x The provided code snippet includes necessary dependencies for implementing the `print_color` function. Write a Python function `def print_color( s, color=None, bold=False, file=sys.stdout)` to solve the following problem: Print a colorized version of string. Here is the function: def print_color( s, color=None, bold=False, file=sys.stdout): # pragma: no cover """Print a colorized version of string.""" if not term_supports_colors(): print(s, file=file) # NOQA elif POSIX: print(hilite(s, color, bold), file=file) # NOQA else: import ctypes DEFAULT_COLOR = 7 GetStdHandle = ctypes.windll.Kernel32.GetStdHandle SetConsoleTextAttribute = \ ctypes.windll.Kernel32.SetConsoleTextAttribute colors = dict(green=2, red=4, brown=6, yellow=6) colors[None] = DEFAULT_COLOR try: color = colors[color] except KeyError: raise ValueError("invalid color %r; choose between %r" % ( color, list(colors.keys()))) if bold and color <= 7: color += 8 handle_id = -12 if file is sys.stderr else -11 GetStdHandle.restype = ctypes.c_ulong handle = GetStdHandle(handle_id) SetConsoleTextAttribute(handle, color) try: print(s, file=file) # NOQA finally: SetConsoleTextAttribute(handle, DEFAULT_COLOR)
Print a colorized version of string.
176,288
import collections import contextlib import errno import functools import os import sys import types def u(s): return s
null
176,289
import collections import contextlib import errno import functools import os import sys import types def u(s): return unicode(s, "unicode_escape")
null
176,290
import collections import contextlib import errno import functools import os import sys import types if PY3: super = super else: _builtin_super = super def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1): """Like Python 3 builtin super(). If called without any arguments it attempts to infer them at runtime. """ if type_ is _SENTINEL: f = sys._getframe(framedepth) try: # Get the function's first positional argument. type_or_obj = f.f_locals[f.f_code.co_varnames[0]] except (IndexError, KeyError): raise RuntimeError('super() used in a function with no args') try: # Get the MRO so we can crawl it. mro = type_or_obj.__mro__ except (AttributeError, RuntimeError): try: mro = type_or_obj.__class__.__mro__ except AttributeError: raise RuntimeError('super() used in a non-newstyle class') for type_ in mro: # Find the class that owns the currently-executing method. for meth in type_.__dict__.values(): # Drill down through any wrappers to the underlying func. # This handles e.g. classmethod() and staticmethod(). try: while not isinstance(meth, types.FunctionType): if isinstance(meth, property): # Calling __get__ on the property will invoke # user code which might throw exceptions or # have side effects meth = meth.fget else: try: meth = meth.__func__ except AttributeError: meth = meth.__get__(type_or_obj, type_) except (AttributeError, TypeError): continue if meth.func_code is f.f_code: break # found else: # Not found. Move onto the next class in MRO. continue break # found else: raise RuntimeError('super() called outside a method') # Dispatch to builtin super(). if type_or_obj is not _SENTINEL: return _builtin_super(type_, type_or_obj) return _builtin_super(type_) import sys if sys.version_info[0] < 3: del num, x def _instance_checking_exception(base_exception=Exception): def wrapped(instance_checker): class TemporaryClass(base_exception): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], TemporaryClass): unwrap_me = args[0] for attr in dir(unwrap_me): if not attr.startswith('__'): setattr(self, attr, getattr(unwrap_me, attr)) else: super(TemporaryClass, self).__init__(*args, **kwargs) class __metaclass__(type): def __instancecheck__(cls, inst): return instance_checker(inst) def __subclasscheck__(cls, classinfo): value = sys.exc_info()[1] return isinstance(value, cls) TemporaryClass.__name__ = instance_checker.__name__ TemporaryClass.__doc__ = instance_checker.__doc__ return TemporaryClass return wrapped
null
176,291
import collections import contextlib import errno import functools import os import sys import types _SENTINEL = object() def FileExistsError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST
null
176,292
import collections import contextlib import errno import functools import os import sys import types try: from functools import lru_cache except ImportError: try: from threading import RLock except ImportError: from dummy_threading import RLock _CacheInfo = collections.namedtuple( "CacheInfo", ["hits", "misses", "maxsize", "currsize"]) def _make_key(args, kwds, typed, kwd_mark=(_SENTINEL, ), fasttypes=set((int, str, frozenset, type(None))), # noqa sorted=sorted, tuple=tuple, type=type, len=len): key = args if kwds: sorted_items = sorted(kwds.items()) key += kwd_mark for item in sorted_items: key += item if typed: key += tuple(type(v) for v in args) if kwds: key += tuple(type(v) for k, v in sorted_items) elif len(key) == 1 and type(key[0]) in fasttypes: return key[0] return _HashedSeq(key) RLock = _RLock The provided code snippet includes necessary dependencies for implementing the `lru_cache` function. Write a Python function `def lru_cache(maxsize=100, typed=False)` to solve the following problem: Least-recently-used cache decorator, see: http://docs.python.org/3/library/functools.html#functools.lru_cache Here is the function: def lru_cache(maxsize=100, typed=False): """Least-recently-used cache decorator, see: http://docs.python.org/3/library/functools.html#functools.lru_cache """ def decorating_function(user_function): cache = dict() stats = [0, 0] HITS, MISSES = 0, 1 make_key = _make_key cache_get = cache.get _len = len lock = RLock() root = [] root[:] = [root, root, None, None] nonlocal_root = [root] PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 if maxsize == 0: def wrapper(*args, **kwds): result = user_function(*args, **kwds) stats[MISSES] += 1 return result elif maxsize is None: def wrapper(*args, **kwds): key = make_key(args, kwds, typed) result = cache_get(key, root) if result is not root: stats[HITS] += 1 return result result = user_function(*args, **kwds) cache[key] = result stats[MISSES] += 1 return result else: def wrapper(*args, **kwds): if kwds or typed: key = make_key(args, kwds, typed) else: key = args lock.acquire() try: link = cache_get(key) if link is not None: root, = nonlocal_root link_prev, link_next, key, result = link link_prev[NEXT] = link_next link_next[PREV] = link_prev last = root[PREV] last[NEXT] = root[PREV] = link link[PREV] = last link[NEXT] = root stats[HITS] += 1 return result finally: lock.release() result = user_function(*args, **kwds) lock.acquire() try: root, = nonlocal_root if key in cache: pass elif _len(cache) >= maxsize: oldroot = root oldroot[KEY] = key oldroot[RESULT] = result root = nonlocal_root[0] = oldroot[NEXT] oldkey = root[KEY] root[KEY] = root[RESULT] = None del cache[oldkey] cache[key] = oldroot else: last = root[PREV] link = [last, root, key, result] last[NEXT] = root[PREV] = cache[key] = link stats[MISSES] += 1 finally: lock.release() return result def cache_info(): """Report cache statistics""" lock.acquire() try: return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache)) finally: lock.release() def cache_clear(): """Clear the cache and cache statistics""" lock.acquire() try: cache.clear() root = nonlocal_root[0] root[:] = [root, root, None, None] stats[:] = [0, 0] finally: lock.release() wrapper.__wrapped__ = user_function wrapper.cache_info = cache_info wrapper.cache_clear = cache_clear return functools.update_wrapper(wrapper, user_function) return decorating_function
Least-recently-used cache decorator, see: http://docs.python.org/3/library/functools.html#functools.lru_cache
176,293
import collections import contextlib import errno import functools import os import sys import types import sys if sys.version_info[0] < 3: del num, x The provided code snippet includes necessary dependencies for implementing the `which` function. Write a Python function `def which(cmd, mode=os.F_OK | os.X_OK, path=None)` to solve the following problem: Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. Here is the function: def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. """ def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd return None if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) if sys.platform == "win32": if os.curdir not in path: path.insert(0, os.curdir) pathext = os.environ.get("PATHEXT", "").split(os.pathsep) if any(cmd.lower().endswith(ext.lower()) for ext in pathext): files = [cmd] else: files = [cmd + ext for ext in pathext] else: files = [cmd] seen = set() for dir in path: normdir = os.path.normcase(dir) if normdir not in seen: seen.add(normdir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path.
176,294
import collections import contextlib import errno import functools import os import sys import types def get_terminal_size(fallback=(80, 24)): try: import fcntl import struct import termios except ImportError: return fallback else: try: # This should work on Linux. res = struct.unpack( 'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')) return (res[1], res[0]) except Exception: return fallback
null