repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
psutil
psutil-master/CONTRIBUTING.md
Contributing to psutil project ============================== Issues ------ * The issue tracker is for reporting problems or proposing enhancements related to the **program code**. * Please do not open issues **asking for support**. Instead, use the forum at: https://groups.google.com/g/psutil. * Before submitting a new issue, **search** if there are existing issues for the same topic. * **Be clear** in describing what the problem is and try to be accurate in editing the default issue **template**. There is a bot which automatically assigns **labels** based on issue's title and body format. Labels help keeping the issues properly organized and searchable (by OS, issue type, etc.). * When reporting a malfunction, consider enabling [debug mode](https://psutil.readthedocs.io/en/latest/#debug-mode) first. * To report a **security vulnerability**, use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and the disclosure of the reported problem. Pull Requests ------------- * The PR system is for fixing bugs or make enhancements related to the **program code**. * If you wish to implement a new feature or add support for a new platform it's better to **discuss it first**, either on the issue tracker, the forum or via private email. * In order to get acquainted with the code base and tooling, take a look at the **[Development Guide](https://github.com/giampaolo/psutil/blob/master/docs/DEVGUIDE.rst)**. * If you can, remember to update [HISTORY.rst](https://github.com/giampaolo/psutil/blob/master/HISTORY.rst) and [CREDITS](https://github.com/giampaolo/psutil/blob/master/CREDITS) file.
1,681
45.722222
93
md
psutil
psutil-master/appveyor.yml
# Build: 3 (bump this up by 1 to force an appveyor run) os: Visual Studio 2015 # avoid 2 builds when pushing on PRs skip_branch_with_pr: true # avoid build on new GIT tag skip_tags: true matrix: # stop build on first failure fast_finish: true environment: global: # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the # /E:ON and /V:ON options are not enabled in the batch script interpreter # See: http://stackoverflow.com/a/13751649/163740 WITH_COMPILER: "cmd /E:ON /V:ON /C .\\scripts\\internal\\appveyor_run_with_compiler.cmd" PYTHONWARNINGS: always PYTHONUNBUFFERED: 1 PSUTIL_DEBUG: 1 matrix: # 32 bits - PYTHON: "C:\\Python27" PYTHON_VERSION: "2.7.x" PYTHON_ARCH: "32" # 64 bits - PYTHON: "C:\\Python27-x64" PYTHON_VERSION: "2.7.x" PYTHON_ARCH: "64" init: - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%" install: - "%WITH_COMPILER% %PYTHON%/python.exe -m pip --version" - "%WITH_COMPILER% %PYTHON%/python.exe -m pip install --upgrade --user setuptools pip" - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py setup-dev-env" - "%WITH_COMPILER% %PYTHON%/python.exe -m pip freeze" - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py install" build: off test_script: - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py test" - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py test-memleaks" after_test: - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/winmake.py wheel" - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/print_hashes.py dist" - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/print_access_denied.py" - "%WITH_COMPILER% %PYTHON%/python.exe scripts/internal/print_api_speed.py" artifacts: - path: dist\* cache: - '%LOCALAPPDATA%\pip\Cache' # on_success: # - might want to upload the content of dist/*.whl to a public wheelhouse skip_commits: message: skip-appveyor # run build only if one of the following files is modified on commit only_commits: files: - .ci/appveyor/* - appveyor.yml - psutil/__init__.py - psutil/_common.py - psutil/_compat.py - psutil/_psutil_common.* - psutil/_psutil_windows.* - psutil/_pswindows.py - psutil/arch/windows/* - psutil/tests/* - scripts/* - scripts/internal/* - setup.py
2,395
27.52381
92
yml
psutil
psutil-master/setup.py
#!/usr/bin/env python3 # Copyright (c) 2009 Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Cross-platform lib for process and system monitoring in Python.""" from __future__ import print_function import contextlib import glob import io import os import platform import re import shutil import struct import subprocess import sys import tempfile import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") try: import setuptools from setuptools import Extension from setuptools import setup except ImportError: setuptools = None from distutils.core import Extension from distutils.core import setup try: from wheel.bdist_wheel import bdist_wheel except ImportError: if "CIBUILDWHEEL" in os.environ: raise bdist_wheel = None HERE = os.path.abspath(os.path.dirname(__file__)) # ...so we can import _common.py and _compat.py sys.path.insert(0, os.path.join(HERE, "psutil")) from _common import AIX # NOQA from _common import BSD # NOQA from _common import FREEBSD # NOQA from _common import LINUX # NOQA from _common import MACOS # NOQA from _common import NETBSD # NOQA from _common import OPENBSD # NOQA from _common import POSIX # NOQA from _common import SUNOS # NOQA from _common import WINDOWS # NOQA from _common import hilite # NOQA from _compat import PY3 # NOQA from _compat import which # NOQA PYPY = '__pypy__' in sys.builtin_module_names PY36_PLUS = sys.version_info[:2] >= (3, 6) PY37_PLUS = sys.version_info[:2] >= (3, 7) CP36_PLUS = PY36_PLUS and sys.implementation.name == "cpython" CP37_PLUS = PY37_PLUS and sys.implementation.name == "cpython" macros = [] if POSIX: macros.append(("PSUTIL_POSIX", 1)) if BSD: macros.append(("PSUTIL_BSD", 1)) # Needed to determine _Py_PARSE_PID in case it's missing (Python 2, PyPy). # Taken from Lib/test/test_fcntl.py. # XXX: not bullet proof as the (long long) case is missing. if struct.calcsize('l') <= 8: macros.append(('PSUTIL_SIZEOF_PID_T', '4')) # int else: macros.append(('PSUTIL_SIZEOF_PID_T', '8')) # long sources = ['psutil/_psutil_common.c'] if POSIX: sources.append('psutil/_psutil_posix.c') extras_require = {"test": [ "enum34; python_version <= '3.4'", "ipaddress; python_version < '3.0'", "mock; python_version < '3.0'", ]} if not PYPY: extras_require['test'].extend([ "pywin32; sys.platform == 'win32'", "wmi; sys.platform == 'win32'"]) def get_version(): INIT = os.path.join(HERE, 'psutil/__init__.py') with open(INIT, 'r') as f: for line in f: if line.startswith('__version__'): ret = eval(line.strip().split(' = ')[1]) assert ret.count('.') == 2, ret for num in ret.split('.'): assert num.isdigit(), ret return ret raise ValueError("couldn't find version string") VERSION = get_version() macros.append(('PSUTIL_VERSION', int(VERSION.replace('.', '')))) # Py_LIMITED_API lets us create a single wheel which works with multiple # python versions, including unreleased ones. if bdist_wheel and CP36_PLUS and (MACOS or LINUX): py_limited_api = {"py_limited_api": True} macros.append(('Py_LIMITED_API', '0x03060000')) elif bdist_wheel and CP37_PLUS and WINDOWS: # PyErr_SetFromWindowsErr / PyErr_SetFromWindowsErrWithFilename are # part of the stable API/ABI starting with CPython 3.7 py_limited_api = {"py_limited_api": True} macros.append(('Py_LIMITED_API', '0x03070000')) else: py_limited_api = {} def get_long_description(): script = os.path.join(HERE, "scripts", "internal", "convert_readme.py") readme = os.path.join(HERE, 'README.rst') p = subprocess.Popen([sys.executable, script, readme], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) stdout, stderr = p.communicate() if p.returncode != 0: raise RuntimeError(stderr) return stdout @contextlib.contextmanager def silenced_output(stream_name): class DummyFile(io.BytesIO): # see: https://github.com/giampaolo/psutil/issues/678 errors = "ignore" def write(self, s): pass orig = getattr(sys, stream_name) try: setattr(sys, stream_name, DummyFile()) yield finally: setattr(sys, stream_name, orig) def missdeps(cmdline): s = "psutil could not be installed from sources" if not SUNOS and not which("gcc"): s += " because gcc is not installed. " else: s += ". Perhaps Python header files are not installed. " s += "Try running:\n" s += " %s" % cmdline print(hilite(s, color="red", bold=True), file=sys.stderr) def unix_can_compile(c_code): from distutils.errors import CompileError from distutils.unixccompiler import UnixCCompiler with tempfile.NamedTemporaryFile( suffix='.c', delete=False, mode="wt") as f: f.write(c_code) tempdir = tempfile.mkdtemp() try: compiler = UnixCCompiler() # https://github.com/giampaolo/psutil/pull/1568 if os.getenv('CC'): compiler.set_executable('compiler_so', os.getenv('CC')) with silenced_output('stderr'): with silenced_output('stdout'): compiler.compile([f.name], output_dir=tempdir) except CompileError: return False else: return True finally: os.remove(f.name) shutil.rmtree(tempdir) if WINDOWS: def get_winver(): maj, min = sys.getwindowsversion()[0:2] return '0x0%s' % ((maj * 100) + min) if sys.getwindowsversion()[0] < 6: msg = "this Windows version is too old (< Windows Vista); " msg += "psutil 3.4.2 is the latest version which supports Windows " msg += "2000, XP and 2003 server" raise RuntimeError(msg) macros.append(("PSUTIL_WINDOWS", 1)) macros.extend([ # be nice to mingw, see: # http://www.mingw.org/wiki/Use_more_recent_defined_functions ('_WIN32_WINNT', get_winver()), ('_AVAIL_WINVER_', get_winver()), ('_CRT_SECURE_NO_WARNINGS', None), # see: https://github.com/giampaolo/psutil/issues/348 ('PSAPI_VERSION', 1), ]) ext = Extension( 'psutil._psutil_windows', sources=( sources + ["psutil/_psutil_windows.c"] + glob.glob("psutil/arch/windows/*.c") ), define_macros=macros, libraries=[ "psapi", "kernel32", "advapi32", "shell32", "netapi32", "ws2_32", "PowrProf", "pdh", ], # extra_compile_args=["/W 4"], # extra_link_args=["/DEBUG"], **py_limited_api ) elif MACOS: macros.append(("PSUTIL_OSX", 1)) ext = Extension( 'psutil._psutil_osx', sources=( sources + ["psutil/_psutil_osx.c"] + glob.glob("psutil/arch/osx/*.c") ), define_macros=macros, extra_link_args=[ '-framework', 'CoreFoundation', '-framework', 'IOKit' ], **py_limited_api) elif FREEBSD: macros.append(("PSUTIL_FREEBSD", 1)) ext = Extension( 'psutil._psutil_bsd', sources=( sources + ["psutil/_psutil_bsd.c"] + glob.glob("psutil/arch/bsd/*.c") + glob.glob("psutil/arch/freebsd/*.c") ), define_macros=macros, libraries=["devstat"], **py_limited_api) elif OPENBSD: macros.append(("PSUTIL_OPENBSD", 1)) ext = Extension( 'psutil._psutil_bsd', sources=( sources + ["psutil/_psutil_bsd.c"] + glob.glob("psutil/arch/bsd/*.c") + glob.glob("psutil/arch/openbsd/*.c") ), define_macros=macros, libraries=["kvm"], **py_limited_api) elif NETBSD: macros.append(("PSUTIL_NETBSD", 1)) ext = Extension( 'psutil._psutil_bsd', sources=( sources + ["psutil/_psutil_bsd.c"] + glob.glob("psutil/arch/bsd/*.c") + glob.glob("psutil/arch/netbsd/*.c") ), define_macros=macros, libraries=["kvm"], **py_limited_api) elif LINUX: # see: https://github.com/giampaolo/psutil/issues/659 if not unix_can_compile("#include <linux/ethtool.h>"): macros.append(("PSUTIL_ETHTOOL_MISSING_TYPES", 1)) macros.append(("PSUTIL_LINUX", 1)) ext = Extension( 'psutil._psutil_linux', sources=sources + ['psutil/_psutil_linux.c'], define_macros=macros, **py_limited_api) elif SUNOS: macros.append(("PSUTIL_SUNOS", 1)) ext = Extension( 'psutil._psutil_sunos', sources=sources + [ 'psutil/_psutil_sunos.c', 'psutil/arch/solaris/v10/ifaddrs.c', 'psutil/arch/solaris/environ.c' ], define_macros=macros, libraries=['kstat', 'nsl', 'socket'], **py_limited_api) elif AIX: macros.append(("PSUTIL_AIX", 1)) ext = Extension( 'psutil._psutil_aix', sources=sources + [ 'psutil/_psutil_aix.c', 'psutil/arch/aix/net_connections.c', 'psutil/arch/aix/common.c', 'psutil/arch/aix/ifaddrs.c'], libraries=['perfstat'], define_macros=macros, **py_limited_api) else: sys.exit('platform %s is not supported' % sys.platform) if POSIX: posix_extension = Extension( 'psutil._psutil_posix', define_macros=macros, sources=sources, **py_limited_api) if SUNOS: def get_sunos_update(): # See https://serverfault.com/q/524883 # for an explanation of Solaris /etc/release with open('/etc/release') as f: update = re.search(r'(?<=s10s_u)[0-9]{1,2}', f.readline()) return int(update.group(0)) if update else 0 posix_extension.libraries.append('socket') if platform.release() == '5.10': # Detect Solaris 5.10, update >= 4, see: # https://github.com/giampaolo/psutil/pull/1638 if get_sunos_update() >= 4: # MIB compliance starts with SunOS 5.10 Update 4: posix_extension.define_macros.append(('NEW_MIB_COMPLIANT', 1)) posix_extension.sources.append('psutil/arch/solaris/v10/ifaddrs.c') posix_extension.define_macros.append(('PSUTIL_SUNOS10', 1)) else: # Other releases are by default considered to be new mib compliant. posix_extension.define_macros.append(('NEW_MIB_COMPLIANT', 1)) elif AIX: posix_extension.sources.append('psutil/arch/aix/ifaddrs.c') extensions = [ext, posix_extension] else: extensions = [ext] cmdclass = {} if py_limited_api: class bdist_wheel_abi3(bdist_wheel): def get_tag(self): python, abi, plat = bdist_wheel.get_tag(self) return python, "abi3", plat cmdclass["bdist_wheel"] = bdist_wheel_abi3 def main(): kwargs = dict( name='psutil', version=VERSION, cmdclass=cmdclass, description=__doc__ .replace('\n', ' ').strip() if __doc__ else '', long_description=get_long_description(), long_description_content_type='text/x-rst', keywords=[ 'ps', 'top', 'kill', 'free', 'lsof', 'netstat', 'nice', 'tty', 'ionice', 'uptime', 'taskmgr', 'process', 'df', 'iotop', 'iostat', 'ifconfig', 'taskset', 'who', 'pidof', 'pmap', 'smem', 'pstree', 'monitoring', 'ulimit', 'prlimit', 'smem', 'performance', 'metrics', 'agent', 'observability', ], author='Giampaolo Rodola', author_email='[email protected]', url='https://github.com/giampaolo/psutil', platforms='Platform Independent', license='BSD-3-Clause', packages=['psutil', 'psutil.tests'], ext_modules=extensions, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Win32 (MS Windows)', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows :: Windows 10', 'Operating System :: Microsoft :: Windows :: Windows 7', 'Operating System :: Microsoft :: Windows :: Windows 8', 'Operating System :: Microsoft :: Windows :: Windows 8.1', 'Operating System :: Microsoft :: Windows :: Windows Server 2003', 'Operating System :: Microsoft :: Windows :: Windows Server 2008', 'Operating System :: Microsoft :: Windows :: Windows Vista', 'Operating System :: Microsoft', 'Operating System :: OS Independent', 'Operating System :: POSIX :: AIX', 'Operating System :: POSIX :: BSD :: FreeBSD', 'Operating System :: POSIX :: BSD :: NetBSD', 'Operating System :: POSIX :: BSD :: OpenBSD', 'Operating System :: POSIX :: BSD', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: SunOS/Solaris', 'Operating System :: POSIX', 'Programming Language :: C', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Benchmark', 'Topic :: System :: Hardware :: Hardware Drivers', 'Topic :: System :: Hardware', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring :: Hardware Watchdog', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Networking', 'Topic :: System :: Operating System', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ], ) if setuptools is not None: kwargs.update( python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*", extras_require=extras_require, zip_safe=False, ) success = False try: setup(**kwargs) success = True finally: cmd = sys.argv[1] if len(sys.argv) >= 2 else '' if not success and POSIX and \ cmd.startswith(("build", "install", "sdist", "bdist", "develop")): py3 = "3" if PY3 else "" if LINUX: pyimpl = "pypy" if PYPY else "python" if which('dpkg'): missdeps("sudo apt-get install gcc %s%s-dev" % (pyimpl, py3)) elif which('rpm'): missdeps("sudo yum install gcc %s%s-devel" % (pyimpl, py3)) elif which('apk'): missdeps("sudo apk add gcc %s%s-dev" % (pyimpl, py3)) elif MACOS: print(hilite("XCode (https://developer.apple.com/xcode/) " "is not installed", color="red"), file=sys.stderr) elif FREEBSD: if which('pkg'): missdeps("pkg install gcc python%s" % py3) elif which('mport'): # MidnightBSD missdeps("mport install gcc python%s" % py3) elif OPENBSD: missdeps("pkg_add -v gcc python%s" % py3) elif NETBSD: missdeps("pkgin install gcc python%s" % py3) elif SUNOS: missdeps("sudo ln -s /usr/bin/gcc /usr/local/bin/cc && " "pkg install gcc") if __name__ == '__main__': main()
16,521
32.787321
79
py
psutil
psutil-master/.github/FUNDING.yml
# These are supported funding model platforms tidelift: "pypi/psutil" github: giampaolo patreon: # Replace with a single Patreon username open_collective: psutil ko_fi: # Replace with a single Ko-fi username community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry custom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A9ZS7PKKRM3S8
392
38.3
91
yml
psutil
psutil-master/.github/PULL_REQUEST_TEMPLATE.md
## Summary * OS: { type-or-version } * Bug fix: { yes/no } * Type: { core, doc, performance, scripts, tests, wheels, new-api } * Fixes: { comma-separated list of issues fixed by this PR, if any } ## Description {{{ A clear explanation of your bugfix or enhancement. Please read the contributing guidelines before submit: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md }}}
396
27.357143
107
md
psutil
psutil-master/.github/no-response.yml
# Configuration for probot-no-response: https://github.com/probot/no-response # Number of days of inactivity before an issue is closed for lack of response daysUntilClose: 14 # Label requiring a response responseRequiredLabel: need-more-info # Comment to post when closing an Issue for lack of response. # Set to `false` to disable closeComment: > This issue has been automatically closed because there has been no response for more information from the original author. Please reach out if you have or find the answers requested so that this can be investigated further.
575
51.363636
225
yml
psutil
psutil-master/.github/ISSUE_TEMPLATE/bug.md
--- name: Bug about: Report a bug title: "[OS] title" labels: 'bug' --- ## Summary * OS: { type-or-version } * Architecture: { 64bit, 32bit, ARM, PowerPC, s390 } * Psutil version: { pip3 show psutil } * Python version: { python3 -V } * Type: { core, doc, performance, scripts, tests, wheels, new-api, installation } ## Description {{{ A clear explanation of the bug, including traceback message (if any). Please read the contributing guidelines before submit: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md }}}
536
23.409091
126
md
psutil
psutil-master/.github/ISSUE_TEMPLATE/config.yml
blank_issues_enabled: false contact_links: - name: Ask a question url: https://groups.google.com/g/psutil about: Use this to ask for support
151
24.333333
43
yml
psutil
psutil-master/.github/ISSUE_TEMPLATE/enhancement.md
--- name: Enhancement about: Propose an enhancement labels: 'enhancement' title: "[OS] title" --- ## Summary * OS: { type-or-version } * Type: { core, doc, performance, scripts, tests, wheels, new-api } ## Description {{{ A clear explanation of your proposal. Please read the contributing guidelines before submit: https://github.com/giampaolo/psutil/blob/master/CONTRIBUTING.md }}}
392
18.65
94
md
psutil
psutil-master/.github/workflows/bsd.yml
# Execute tests on *BSD platforms. Does not produce wheels. # Useful URLs: # https://github.com/vmactions/freebsd-vm # https://github.com/vmactions/openbsd-vm # https://github.com/vmactions/netbsd-vm on: [push, pull_request] name: bsd-tests concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.sha || '' }} cancel-in-progress: true jobs: freebsd: runs-on: macos-12 steps: - uses: actions/checkout@v3 - name: Run tests uses: vmactions/freebsd-vm@v0 with: usesh: true prepare: | pkg install -y gcc python3 run: | set -e -x make install-pip python3 -m pip install --user setuptools make install make test make test-memleaks openbsd: runs-on: macos-12 steps: - uses: actions/checkout@v3 - name: Run tests uses: vmactions/openbsd-vm@v0 with: usesh: true prepare: | set -e pkg_add gcc python3 run: | set -e make install-pip python3 -m pip install --user setuptools make install make test make test-memleaks netbsd: runs-on: macos-12 steps: - uses: actions/checkout@v3 - name: Run tests uses: vmactions/netbsd-vm@v0 with: usesh: true prepare: | set -e pkg_add -v pkgin pkgin update pkgin -y install python311-* py311-setuptools-* gcc12-* run: | set -e make install-pip PYTHON=python3.11 python3.11 -m pip install --user setuptools make install PYTHON=python3.11 make test PYTHON=python3.11 make test-memleaks PYTHON=python3.11
1,955
27.764706
180
yml
psutil
psutil-master/.github/workflows/build.yml
# Runs CI tests and generates wheels on the following platforms: # # * Linux (py2 and py3) # * macOS (py2 and py3) # * Windows (py3, py2 is done by appveyor) # # Useful URLs: # * https://github.com/pypa/cibuildwheel # * https://github.com/actions/checkout # * https://github.com/actions/setup-python # * https://github.com/actions/upload-artifact # * https://github.com/marketplace/actions/cancel-workflow-action on: [push, pull_request] name: build jobs: # Linux + macOS + Windows Python 3 py3: name: py3-${{ matrix.os }}-${{ startsWith(matrix.os, 'windows') && matrix.archs || 'all' }} runs-on: ${{ matrix.os }} timeout-minutes: 20 strategy: fail-fast: false matrix: include: - os: ubuntu-latest archs: "x86_64 i686" - os: macos-12 archs: "x86_64 arm64" - os: windows-2019 archs: "AMD64" - os: windows-2019 archs: "x86" steps: - name: Cancel previous runs uses: styfle/[email protected] with: access_token: ${{ github.token }} - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.11 - name: Create wheels + run tests uses: pypa/[email protected] env: CIBW_ARCHS: "${{ matrix.archs }}" - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: wheelhouse - name: Generate .tar.gz if: matrix.os == 'ubuntu-latest' run: | make generate-manifest python setup.py sdist mv dist/psutil*.tar.gz wheelhouse/ # Linux + macOS + Python 2 py2: name: py2-${{ matrix.os }} runs-on: ${{ matrix.os }} timeout-minutes: 20 strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-12] env: CIBW_TEST_COMMAND: PYTHONWARNINGS=always PYTHONUNBUFFERED=1 PSUTIL_DEBUG=1 python {project}/psutil/tests/runner.py && PYTHONWARNINGS=always PYTHONUNBUFFERED=1 PSUTIL_DEBUG=1 python {project}/psutil/tests/test_memleaks.py CIBW_TEST_EXTRAS: test CIBW_BUILD: 'cp27-*' steps: - name: Cancel previous runs uses: styfle/[email protected] with: access_token: ${{ github.token }} - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.9 - name: Create wheels + run tests uses: pypa/[email protected] - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: wheelhouse - name: Generate .tar.gz if: matrix.os == 'ubuntu-latest' run: | make generate-manifest python setup.py sdist mv dist/psutil*.tar.gz wheelhouse/ # Run linters linters: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 - name: 'Run linters' run: | # py3 python3 -m pip install flake8 isort python3 -m flake8 . python3 -m isort . # clinter find . -type f \( -iname "*.c" -o -iname "*.h" \) | xargs python3 scripts/internal/clinter.py # Check sanity of .tar.gz + wheel files check-dist: needs: [py2, py3] runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.x - uses: actions/download-artifact@v3 with: name: wheels path: wheelhouse - run: | python scripts/internal/print_hashes.py wheelhouse/ pipx run twine check --strict wheelhouse/* pipx run abi3audit --verbose --strict wheelhouse/*-abi3-*.whl
3,742
25.928058
110
yml
psutil
psutil-master/.github/workflows/issues.py
#!/usr/bin/env python3 # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Bot triggered by Github Actions every time a new issue, PR or comment is created. Assign labels, provide replies, closes issues, etc. depending on the situation. """ from __future__ import print_function import functools import json import os import re from pprint import pprint as pp from github import Github ROOT_DIR = os.path.realpath( os.path.join(os.path.dirname(__file__), '..', '..')) SCRIPTS_DIR = os.path.join(ROOT_DIR, 'scripts') # --- constants LABELS_MAP = { # platforms "linux": [ "linux", "ubuntu", "redhat", "mint", "centos", "red hat", "archlinux", "debian", "alpine", "gentoo", "fedora", "slackware", "suse", "RHEL", "opensuse", "manylinux", "apt ", "apt-", "rpm", "yum", "kali", "/sys/class", "/proc/net", "/proc/disk", "/proc/smaps", "/proc/vmstat", ], "windows": [ "windows", "win32", "WinError", "WindowsError", "win10", "win7", "win ", "mingw", "msys", "studio", "microsoft", "make.bat", "CloseHandle", "GetLastError", "NtQuery", "DLL", "MSVC", "TCHAR", "WCHAR", ".bat", "OpenProcess", "TerminateProcess", "appveyor", "windows error", "NtWow64", "NTSTATUS", "Visual Studio", ], "macos": [ "macos", "mac ", "osx", "os x", "mojave", "sierra", "capitan", "yosemite", "catalina", "mojave", "big sur", "xcode", "darwin", "dylib", "m1", ], "aix": ["aix"], "cygwin": ["cygwin"], "freebsd": ["freebsd"], "netbsd": ["netbsd"], "openbsd": ["openbsd"], "sunos": ["sunos", "solaris"], "wsl": ["wsl"], "unix": [ "psposix", "_psutil_posix", "waitpid", "statvfs", "/dev/tty", "/dev/pts", "posix", ], "pypy": ["pypy"], # types "enhancement": ["enhancement"], "memleak": ["memory leak", "leaks memory", "memleak", "mem leak"], "api": ["idea", "proposal", "api", "feature"], "performance": ["performance", "speedup", "speed up", "slow", "fast"], "wheels": ["wheel", "wheels"], "scripts": [ "example script", "examples script", "example dir", "scripts/", ], # bug "bug": [ "fail", "can't execute", "can't install", "cannot execute", "cannot install", "install error", "crash", "critical", ], # doc "doc": [ "doc ", "document ", "documentation", "readthedocs", "pythonhosted", "HISTORY", "README", "dev guide", "devguide", "sphinx", "docfix", "index.rst", ], # tests "tests": [ " test ", "tests", "travis", "coverage", "cirrus", "appveyor", "continuous integration", "unittest", "pytest", "unit test", ], # critical errors "priority-high": [ "WinError", "WindowsError", "RuntimeError", "ZeroDivisionError", "SystemError", "MemoryError", "core dumped", "segfault", "segmentation fault", ], } LABELS_MAP['scripts'].extend( [x for x in os.listdir(SCRIPTS_DIR) if x.endswith('.py')]) OS_LABELS = [ "linux", "windows", "macos", "freebsd", "openbsd", "netbsd", "openbsd", "bsd", "sunos", "unix", "wsl", "aix", "cygwin", ] ILLOGICAL_PAIRS = [ ('bug', 'enhancement'), ('doc', 'tests'), ('scripts', 'doc'), ('scripts', 'tests'), ('bsd', 'freebsd'), ('bsd', 'openbsd'), ('bsd', 'netbsd'), ] # --- replies REPLY_MISSING_PYTHON_HEADERS = """\ It looks like you're missing `Python.h` headers. This usually means you have \ to install them first, then retry psutil installation. Please read \ [INSTALL](https://github.com/giampaolo/psutil/blob/master/INSTALL.rst) \ instructions for your platform. \ This is an auto-generated response based on the text you submitted. \ If this was a mistake or you think there's a bug with psutil installation \ process, please add a comment to reopen this issue. """ # REPLY_UPDATE_CHANGELOG = """\ # """ # --- github API utils def is_pr(issue): return issue.pull_request is not None def has_label(issue, label): assigned = [x.name for x in issue.labels] return label in assigned def has_os_label(issue): labels = set([x.name for x in issue.labels]) for label in OS_LABELS: if label in labels: return True return False def get_repo(): repo = os.environ['GITHUB_REPOSITORY'] token = os.environ['GITHUB_TOKEN'] return Github(token).get_repo(repo) # --- event utils @functools.lru_cache() def _get_event_data(): ret = json.load(open(os.environ["GITHUB_EVENT_PATH"])) pp(ret) return ret def is_event_new_issue(): data = _get_event_data() try: return data['action'] == 'opened' and 'issue' in data except KeyError: return False def is_event_new_pr(): data = _get_event_data() try: return data['action'] == 'opened' and 'pull_request' in data except KeyError: return False def get_issue(): data = _get_event_data() try: num = data['issue']['number'] except KeyError: num = data['pull_request']['number'] return get_repo().get_issue(number=num) # --- actions def log(msg): if '\n' in msg or "\r\n" in msg: print(">>>\n%s\n<<<" % msg, flush=True) else: print(">>> %s <<<" % msg, flush=True) def add_label(issue, label): def should_add(issue, label): if has_label(issue, label): log("already has label %r" % (label)) return False for left, right in ILLOGICAL_PAIRS: if label == left and has_label(issue, right): log("already has label" % (label)) return False return not has_label(issue, label) if not should_add(issue, label): log("should not add label %r" % label) return log("add label %r" % label) issue.add_to_labels(label) def _guess_labels_from_text(text): assert isinstance(text, str), text for label, keywords in LABELS_MAP.items(): for keyword in keywords: if keyword.lower() in text.lower(): yield (label, keyword) def add_labels_from_text(issue, text): assert isinstance(text, str), text for label, keyword in _guess_labels_from_text(text): add_label(issue, label) def add_labels_from_new_body(issue, text): assert isinstance(text, str), text log("start searching for template lines in new issue/PR body") # add os label r = re.search(r"\* OS:.*?\n", text) log("search for 'OS: ...' line") if r: log("found") add_labels_from_text(issue, r.group(0)) else: log("not found") # add bug/enhancement label log("search for 'Bug fix: y/n' line") r = re.search(r"\* Bug fix:.*?\n", text) if is_pr(issue) and \ r is not None and \ not has_label(issue, "bug") and \ not has_label(issue, "enhancement"): log("found") s = r.group(0).lower() if 'yes' in s: add_label(issue, 'bug') else: add_label(issue, 'enhancement') else: log("not found") # add type labels log("search for 'Type: ...' line") r = re.search(r"\* Type:.*?\n", text) if r: log("found") s = r.group(0).lower() if 'doc' in s: add_label(issue, 'doc') if 'performance' in s: add_label(issue, 'performance') if 'scripts' in s: add_label(issue, 'scripts') if 'tests' in s: add_label(issue, 'tests') if 'wheels' in s: add_label(issue, 'wheels') if 'new-api' in s: add_label(issue, 'new-api') if 'new-platform' in s: add_label(issue, 'new-platform') else: log("not found") # --- events def on_new_issue(issue): def has_text(text): return text in issue.title.lower() or \ (issue.body and text in issue.body.lower()) def body_mentions_python_h(): if not issue.body: return False body = issue.body.replace(' ', '') return "#include<Python.h>\n^~~~" in body or \ "#include<Python.h>\r\n^~~~" in body log("searching for missing Python.h") if has_text("missing python.h") or \ has_text("python.h: no such file or directory") or \ body_mentions_python_h(): log("found mention of Python.h") issue.create_comment(REPLY_MISSING_PYTHON_HEADERS) issue.edit(state='closed') return def on_new_pr(issue): pass # pr = get_repo().get_pull(issue.number) # files = [x.filename for x in list(pr.get_files())] # if "HISTORY.rst" not in files: # issue.create_comment(REPLY_UPDATE_CHANGELOG) def main(): issue = get_issue() stype = "PR" if is_pr(issue) else "issue" log("running issue bot for %s %r" % (stype, issue)) if is_event_new_issue(): log("created new issue %s" % issue) add_labels_from_text(issue, issue.title) if issue.body: add_labels_from_new_body(issue, issue.body) on_new_issue(issue) elif is_event_new_pr(): log("created new PR %s" % issue) add_labels_from_text(issue, issue.title) if issue.body: add_labels_from_new_body(issue, issue.body) on_new_pr(issue) else: log("unhandled event") if __name__ == '__main__': main()
9,551
26.527378
78
py
psutil
psutil-master/.github/workflows/issues.yml
# Fired by Github Actions every time an issue, PR or comment is created. name: issues on: issues: types: [opened] pull_request: typed: [opened] issue_comment: types: [created] jobs: build: runs-on: ubuntu-latest steps: # install python - uses: actions/checkout@v3 - name: Install Python uses: actions/setup-python@v4 with: python-version: '3.x' # install deps - name: Install deps run: python3 -m pip install PyGithub # run - name: Run env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | PYTHONUNBUFFERED=1 PYTHONWARNINGS=always python3 .github/workflows/issues.py
680
20.28125
84
yml
psutil
psutil-master/docs/conf.py
# -*- coding: utf-8 -*- # # psutil documentation build configuration file, created by # sphinx-quickstart on Wed Oct 19 21:54:30 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ import datetime import os PROJECT_NAME = "psutil" AUTHOR = u"Giampaolo Rodola" THIS_YEAR = str(datetime.datetime.now().year) HERE = os.path.abspath(os.path.dirname(__file__)) def get_version(): INIT = os.path.abspath(os.path.join(HERE, '../psutil/__init__.py')) with open(INIT, 'r') as f: for line in f: if line.startswith('__version__'): ret = eval(line.strip().split(' = ')[1]) assert ret.count('.') == 2, ret for num in ret.split('.'): assert num.isdigit(), ret return ret else: raise ValueError("couldn't find version string") VERSION = get_version() # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.imgmath', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = PROJECT_NAME copyright = '2009-%s, %s' % (THIS_YEAR, AUTHOR) author = AUTHOR # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = VERSION # The full version, including alpha/beta/rc tags. release = VERSION # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = "eng" # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'DEVGUIDE.rst'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # # html_title = u'psutil v1.0' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or # 32x32 pixels large. # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = '%s-doc' % PROJECT_NAME # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'psutil.tex', u'psutil Documentation', AUTHOR, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # It false, will not define \strong, \code, itleref, \crossref ... but only # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added # packages. # # latex_keep_old_macro_names = True # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'psutil', u'psutil Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'psutil', u'psutil Documentation', author, 'psutil', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False html_context = { 'css_files': [ 'https://media.readthedocs.org/css/sphinx_rtd_theme.css', 'https://media.readthedocs.org/css/readthedocs-doc-embed.css', '_static/css/custom.css', ], }
10,839
27.753316
79
py
psutil
psutil-master/docs/_static/css/custom.css
.wy-nav-content { max-width: 100% !important; padding: 15px !important; } .rst-content dl:not(.docutils) { margin: 0px 0px 0px 0px !important; } .data dd { margin-bottom: 0px !important; } .data .descname { border-right:10px !important; } .local-toc li ul li { padding-left: 20px !important; } .rst-content ul p { margin-bottom: 0px !important; } .document td { padding-bottom: 0px !important; } .document th { padding-top: 0px !important; padding-bottom: 0px !important; } .document th p { margin-bottom: 0px !important; } .document th p { } .function .descclassname { font-weight: normal !important; } .class .descclassname { font-weight: normal !important; } .admonition.warning { padding-top: 2px !important; padding-bottom: 2px !important; } .admonition.note { padding-top: 2px !important; padding-bottom: 2px !important; } .rst-content dl:not(.docutils) dt { color: #555; } .sig-paren { padding-left: 2px; padding-right: 2px; } h1, h2, h3 { background: #eee; padding: 5px; border-bottom: 1px solid #ccc; } h1 { font-size: 35px; } .admonition.warning { padding-top: 5px !important; padding-bottom: 5px !important; } .admonition.warning p { margin-bottom: 5px !important; } .admonition.note { padding-top: 5px !important; padding-bottom: 5px !important; } .admonition.note p { margin-bottom: 5px !important; backround-color: rgb(238, 255, 204) !important; } .codeblock div[class^='highlight'], pre.literal-block div[class^='highlight'], .rst-content .literal-block div[class^='highlight'], div[class^='highlight'] div[class^='highlight'] { background-color: #eeffcc !important; } .highlight .hll { background-color: #ffffcc } .highlight { background: #eeffcc; } .highlight-default, .highlight-python { border-radius: 3px !important; border: 1px solid #ac9 !important; } .highlight .c { color: #408090; font-style: italic } .wy-side-nav-search { background-color: grey !important } .highlight { border-radius: 3px !important; } div.highlight-default { margin-bottom: 10px !important; } pre { padding: 5px !important; } /* ================================================================== */ /* Warnings and info boxes like python doc */ /* ================================================================== */ div.admonition { margin-top: 10px !important; margin-bottom: 10px !important; } div.warning { background-color: #ffe4e4 !important; border: 1px solid #f66 !important; border-radius: 3px !important; } div.note { background-color: #eee !important; border: 1px solid #ccc !important; border-radius: 3px !important; } div.admonition p.admonition-title + p { display: inline !important; } p.admonition-title { display: inline !important; background: none !important; color: black !important; } p.admonition-title:after { content: ":" !important; } div.body div.admonition, div.body div.impl-detail { } .fa-exclamation-circle:before, .wy-inline-validate.wy-inline-validate-warning .wy-input-context:before, .wy-inline-validate.wy-inline-validate-info .wy-input-context:before, .rst-content .admonition-title:before { display: none !important; } .note code { background: #d6d6d6 !important; } /* ================================================================== */ /* Syntax highlight like Python doc. /* ================================================================== */ /* Comment */ .highlight .err { border: 1px solid #FF0000 } /* Error */ .highlight .k { color: #007020; font-weight: bold } /* Keyword */ .highlight .o { color: #666666 } /* Operator */ .highlight .ch { color: #408090; font-style: italic } /* Comment.Hashbang */ .highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */ .highlight .cp { color: #007020 } /* Comment.Preproc */ .highlight .cpf { color: #408090; font-style: italic } /* Comment.PreprocFile */ .highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */ .highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #A00000 } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #FF0000 } /* Generic.Error */ .highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .highlight .gi { color: #00A000 } /* Generic.Inserted */ .highlight .go { color: #333333 } /* Generic.Output */ .highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .highlight .gt { color: #0044DD } /* Generic.Traceback */ .highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #007020 } /* Keyword.Pseudo */ .highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #902000 } /* Keyword.Type */ .highlight .m { color: #208050 } /* Literal.Number */ .highlight .s { color: #4070a0 } /* Literal.String */ .highlight .na { color: #4070a0 } /* Name.Attribute */ .highlight .nb { color: #007020 } /* Name.Builtin */ .highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */ .highlight .no { color: #60add5 } /* Name.Constant */ .highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */ .highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */ .highlight .ne { color: #007020 } /* Name.Exception */ .highlight .nf { color: #06287e } /* Name.Function */ .highlight .nl { color: #002070; font-weight: bold } /* Name.Label */ .highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ .highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #bb60d5 } /* Name.Variable */ .highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #208050 } /* Literal.Number.Bin */ .highlight .mf { color: #208050 } /* Literal.Number.Float */ .highlight .mh { color: #208050 } /* Literal.Number.Hex */ .highlight .mi { color: #208050 } /* Literal.Number.Integer */ .highlight .mo { color: #208050 } /* Literal.Number.Oct */ .highlight .sa { color: #4070a0 } /* Literal.String.Affix */ .highlight .sb { color: #4070a0 } /* Literal.String.Backtick */ .highlight .sc { color: #4070a0 } /* Literal.String.Char */ .highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */ .highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */ .highlight .s2 { color: #4070a0 } /* Literal.String.Double */ .highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */ .highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */ .highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */ .highlight .sx { color: #c65d09 } /* Literal.String.Other */ .highlight .sr { color: #235388 } /* Literal.String.Regex */ .highlight .s1 { color: #4070a0 } /* Literal.String.Single */ .highlight .ss { color: #517918 } /* Literal.String.Symbol */ .highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #06287e } /* Name.Function.Magic */ .highlight .vc { color: #bb60d5 } /* Name.Variable.Class */ .highlight .vg { color: #bb60d5 } /* Name.Variable.Global */ .highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */ .highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */ .highlight .il { color: #208050 }
8,199
14.213358
213
css
psutil
psutil-master/psutil/__init__.py
# -*- coding: utf-8 -*- # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """psutil is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. Supported platforms: - Linux - Windows - macOS - FreeBSD - OpenBSD - NetBSD - Sun Solaris - AIX Works with Python versions 2.7 and 3.4+. """ from __future__ import division import collections import contextlib import datetime import functools import os import signal import subprocess import sys import threading import time try: import pwd except ImportError: pwd = None from . import _common from ._common import AIX from ._common import BSD from ._common import CONN_CLOSE from ._common import CONN_CLOSE_WAIT from ._common import CONN_CLOSING from ._common import CONN_ESTABLISHED from ._common import CONN_FIN_WAIT1 from ._common import CONN_FIN_WAIT2 from ._common import CONN_LAST_ACK from ._common import CONN_LISTEN from ._common import CONN_NONE from ._common import CONN_SYN_RECV from ._common import CONN_SYN_SENT from ._common import CONN_TIME_WAIT from ._common import FREEBSD # NOQA from ._common import LINUX from ._common import MACOS from ._common import NETBSD # NOQA from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN from ._common import OPENBSD # NOQA from ._common import OSX # deprecated alias from ._common import POSIX # NOQA from ._common import POWER_TIME_UNKNOWN from ._common import POWER_TIME_UNLIMITED from ._common import STATUS_DEAD from ._common import STATUS_DISK_SLEEP from ._common import STATUS_IDLE from ._common import STATUS_LOCKED from ._common import STATUS_PARKED from ._common import STATUS_RUNNING from ._common import STATUS_SLEEPING from ._common import STATUS_STOPPED from ._common import STATUS_TRACING_STOP from ._common import STATUS_WAITING from ._common import STATUS_WAKING from ._common import STATUS_ZOMBIE from ._common import SUNOS from ._common import WINDOWS from ._common import AccessDenied from ._common import Error from ._common import NoSuchProcess from ._common import TimeoutExpired from ._common import ZombieProcess from ._common import memoize_when_activated from ._common import wrap_numbers as _wrap_numbers from ._compat import PY3 as _PY3 from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import SubprocessTimeoutExpired as _SubprocessTimeoutExpired from ._compat import long if LINUX: # This is public API and it will be retrieved from _pslinux.py # via sys.modules. PROCFS_PATH = "/proc" from . import _pslinux as _psplatform from ._pslinux import IOPRIO_CLASS_BE # NOQA from ._pslinux import IOPRIO_CLASS_IDLE # NOQA from ._pslinux import IOPRIO_CLASS_NONE # NOQA from ._pslinux import IOPRIO_CLASS_RT # NOQA elif WINDOWS: from . import _pswindows as _psplatform from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA from ._pswindows import CONN_DELETE_TCB # NOQA from ._pswindows import IOPRIO_HIGH # NOQA from ._pswindows import IOPRIO_LOW # NOQA from ._pswindows import IOPRIO_NORMAL # NOQA from ._pswindows import IOPRIO_VERYLOW # NOQA elif MACOS: from . import _psosx as _psplatform elif BSD: from . import _psbsd as _psplatform elif SUNOS: from . import _pssunos as _psplatform from ._pssunos import CONN_BOUND # NOQA from ._pssunos import CONN_IDLE # NOQA # This is public writable API which is read from _pslinux.py and # _pssunos.py via sys.modules. PROCFS_PATH = "/proc" elif AIX: from . import _psaix as _psplatform # This is public API and it will be retrieved from _pslinux.py # via sys.modules. PROCFS_PATH = "/proc" else: # pragma: no cover raise NotImplementedError('platform %s is not supported' % sys.platform) __all__ = [ # exceptions "Error", "NoSuchProcess", "ZombieProcess", "AccessDenied", "TimeoutExpired", # constants "version_info", "__version__", "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP", "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD", "STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED", "STATUS_PARKED", "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1", "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT", "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE", # "CONN_IDLE", "CONN_BOUND", "AF_LINK", "NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN", "POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED", "BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX", "SUNOS", "WINDOWS", "AIX", # "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA", # "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE", # "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE", # "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING", # classes "Process", "Popen", # functions "pid_exists", "pids", "process_iter", "wait_procs", # proc "virtual_memory", "swap_memory", # memory "cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu "cpu_stats", # "cpu_freq", "getloadavg" "net_io_counters", "net_connections", "net_if_addrs", # network "net_if_stats", "disk_io_counters", "disk_partitions", "disk_usage", # disk # "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors "users", "boot_time", # others ] __all__.extend(_psplatform.__extra__all__) # Linux, FreeBSD if hasattr(_psplatform.Process, "rlimit"): # Populate global namespace with RLIM* constants. from . import _psutil_posix _globals = globals() _name = None for _name in dir(_psutil_posix): if _name.startswith('RLIM') and _name.isupper(): _globals[_name] = getattr(_psutil_posix, _name) __all__.append(_name) del _globals, _name AF_LINK = _psplatform.AF_LINK __author__ = "Giampaolo Rodola'" __version__ = "5.9.5" version_info = tuple([int(num) for num in __version__.split('.')]) _timer = getattr(time, 'monotonic', time.time) _TOTAL_PHYMEM = None _LOWEST_PID = None _SENTINEL = object() # Sanity check in case the user messed up with psutil installation # or did something weird with sys.path. In this case we might end # up importing a python module using a C extension module which # was compiled for a different version of psutil. # We want to prevent that by failing sooner rather than later. # See: https://github.com/giampaolo/psutil/issues/564 if (int(__version__.replace('.', '')) != getattr(_psplatform.cext, 'version', None)): msg = "version conflict: %r C extension module was built for another " \ "version of psutil" % _psplatform.cext.__file__ if hasattr(_psplatform.cext, 'version'): msg += " (%s instead of %s)" % ( '.'.join([x for x in str(_psplatform.cext.version)]), __version__) else: msg += " (different than %s)" % __version__ msg += "; you may try to 'pip uninstall psutil', manually remove %s" % ( getattr(_psplatform.cext, "__file__", "the existing psutil install directory")) msg += " or clean the virtual env somehow, then reinstall" raise ImportError(msg) # ===================================================================== # --- Utils # ===================================================================== if hasattr(_psplatform, 'ppid_map'): # Faster version (Windows and Linux). _ppid_map = _psplatform.ppid_map else: # pragma: no cover def _ppid_map(): """Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). """ ret = {} for pid in pids(): try: ret[pid] = _psplatform.Process(pid).ppid() except (NoSuchProcess, ZombieProcess): pass return ret def _assert_pid_not_reused(fun): """Decorator which raises NoSuchProcess in case a process is no longer running or its PID has been reused. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): if not self.is_running(): if self._pid_reused: msg = "process no longer exists and its PID has been reused" else: msg = None raise NoSuchProcess(self.pid, self._name, msg=msg) return fun(self, *args, **kwargs) return wrapper def _pprint_secs(secs): """Format seconds in a human readable form.""" now = time.time() secs_ago = int(now - secs) if secs_ago < 60 * 60 * 24: fmt = "%H:%M:%S" else: fmt = "%Y-%m-%d %H:%M:%S" return datetime.datetime.fromtimestamp(secs).strftime(fmt) # ===================================================================== # --- Process class # ===================================================================== class Process(object): """Represents an OS process with the given PID. If PID is omitted current process PID (os.getpid()) is used. Raise NoSuchProcess if PID does not exist. Note that most of the methods of this class do not make sure the PID of the process being queried has been reused over time. That means you might end up retrieving an information referring to another process in case the original one this instance refers to is gone in the meantime. The only exceptions for which process identity is pre-emptively checked and guaranteed are: - parent() - children() - nice() (set) - ionice() (set) - rlimit() (set) - cpu_affinity (set) - suspend() - resume() - send_signal() - terminate() - kill() To prevent this problem for all other methods you can: - use is_running() before querying the process - if you're continuously iterating over a set of Process instances use process_iter() which pre-emptively checks process identity for every yielded instance """ def __init__(self, pid=None): self._init(pid) def _init(self, pid, _ignore_nsp=False): if pid is None: pid = os.getpid() else: if not _PY3 and not isinstance(pid, (int, long)): raise TypeError('pid must be an integer (got %r)' % pid) if pid < 0: raise ValueError('pid must be a positive integer (got %s)' % pid) try: _psplatform.cext.check_pid_range(pid) except OverflowError: raise NoSuchProcess( pid, msg='process PID out of range (got %s)' % pid, ) self._pid = pid self._name = None self._exe = None self._create_time = None self._gone = False self._pid_reused = False self._hash = None self._lock = threading.RLock() # used for caching on Windows only (on POSIX ppid may change) self._ppid = None # platform-specific modules define an _psplatform.Process # implementation class self._proc = _psplatform.Process(pid) self._last_sys_cpu_times = None self._last_proc_cpu_times = None self._exitcode = _SENTINEL # cache creation time for later use in is_running() method try: self.create_time() except AccessDenied: # We should never get here as AFAIK we're able to get # process creation time on all platforms even as a # limited user. pass except ZombieProcess: # Zombies can still be queried by this class (although # not always) and pids() return them so just go on. pass except NoSuchProcess: if not _ignore_nsp: raise NoSuchProcess(pid, msg='process PID not found') else: self._gone = True # This pair is supposed to identify a Process instance # univocally over time (the PID alone is not enough as # it might refer to a process whose PID has been reused). # This will be used later in __eq__() and is_running(). self._ident = (self.pid, self._create_time) def __str__(self): info = collections.OrderedDict() info["pid"] = self.pid if self._name: info['name'] = self._name with self.oneshot(): try: info["name"] = self.name() info["status"] = self.status() except ZombieProcess: info["status"] = "zombie" except NoSuchProcess: info["status"] = "terminated" except AccessDenied: pass if self._exitcode not in (_SENTINEL, None): info["exitcode"] = self._exitcode if self._create_time: info['started'] = _pprint_secs(self._create_time) return "%s.%s(%s)" % ( self.__class__.__module__, self.__class__.__name__, ", ".join(["%s=%r" % (k, v) for k, v in info.items()])) __repr__ = __str__ def __eq__(self, other): # Test for equality with another Process object based # on PID and creation time. if not isinstance(other, Process): return NotImplemented return self._ident == other._ident def __ne__(self, other): return not self == other def __hash__(self): if self._hash is None: self._hash = hash(self._ident) return self._hash @property def pid(self): """The process PID.""" return self._pid # --- utility methods @contextlib.contextmanager def oneshot(self): """Utility context manager which considerably speeds up the retrieval of multiple process information at the same time. Internally different process info (e.g. name, ppid, uids, gids, ...) may be fetched by using the same routine, but only one information is returned and the others are discarded. When using this context manager the internal routine is executed once (in the example below on name()) and the other info are cached. The cache is cleared when exiting the context manager block. The advice is to use this every time you retrieve more than one information about the process. If you're lucky, you'll get a hell of a speedup. >>> import psutil >>> p = psutil.Process() >>> with p.oneshot(): ... p.name() # collect multiple info ... p.cpu_times() # return cached value ... p.cpu_percent() # return cached value ... p.create_time() # return cached value ... >>> """ with self._lock: if hasattr(self, "_cache"): # NOOP: this covers the use case where the user enters the # context twice: # # >>> with p.oneshot(): # ... with p.oneshot(): # ... # # Also, since as_dict() internally uses oneshot() # I expect that the code below will be a pretty common # "mistake" that the user will make, so let's guard # against that: # # >>> with p.oneshot(): # ... p.as_dict() # ... yield else: try: # cached in case cpu_percent() is used self.cpu_times.cache_activate(self) # cached in case memory_percent() is used self.memory_info.cache_activate(self) # cached in case parent() is used self.ppid.cache_activate(self) # cached in case username() is used if POSIX: self.uids.cache_activate(self) # specific implementation cache self._proc.oneshot_enter() yield finally: self.cpu_times.cache_deactivate(self) self.memory_info.cache_deactivate(self) self.ppid.cache_deactivate(self) if POSIX: self.uids.cache_deactivate(self) self._proc.oneshot_exit() def as_dict(self, attrs=None, ad_value=None): """Utility method returning process information as a hashable dictionary. If *attrs* is specified it must be a list of strings reflecting available Process class' attribute names (e.g. ['cpu_times', 'name']) else all public (read only) attributes are assumed. *ad_value* is the value which gets assigned in case AccessDenied or ZombieProcess exception is raised when retrieving that particular process information. """ valid_names = _as_dict_attrnames if attrs is not None: if not isinstance(attrs, (list, tuple, set, frozenset)): raise TypeError("invalid attrs type %s" % type(attrs)) attrs = set(attrs) invalid_names = attrs - valid_names if invalid_names: raise ValueError("invalid attr name%s %s" % ( "s" if len(invalid_names) > 1 else "", ", ".join(map(repr, invalid_names)))) retdict = {} ls = attrs or valid_names with self.oneshot(): for name in ls: try: if name == 'pid': ret = self.pid else: meth = getattr(self, name) ret = meth() except (AccessDenied, ZombieProcess): ret = ad_value except NotImplementedError: # in case of not implemented functionality (may happen # on old or exotic systems) we want to crash only if # the user explicitly asked for that particular attr if attrs: raise continue retdict[name] = ret return retdict def parent(self): """Return the parent process as a Process object pre-emptively checking whether PID has been reused. If no parent is known return None. """ lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0] if self.pid == lowest_pid: return None ppid = self.ppid() if ppid is not None: ctime = self.create_time() try: parent = Process(ppid) if parent.create_time() <= ctime: return parent # ...else ppid has been reused by another process except NoSuchProcess: pass def parents(self): """Return the parents of this process as a list of Process instances. If no parents are known return an empty list. """ parents = [] proc = self.parent() while proc is not None: parents.append(proc) proc = proc.parent() return parents def is_running(self): """Return whether this process is running. It also checks if PID has been reused by another process in which case return False. """ if self._gone or self._pid_reused: return False try: # Checking if PID is alive is not enough as the PID might # have been reused by another process: we also want to # verify process identity. # Process identity / uniqueness over time is guaranteed by # (PID + creation time) and that is verified in __eq__. self._pid_reused = self != Process(self.pid) return not self._pid_reused except ZombieProcess: # We should never get here as it's already handled in # Process.__init__; here just for extra safety. return True except NoSuchProcess: self._gone = True return False # --- actual API @memoize_when_activated def ppid(self): """The process parent PID. On Windows the return value is cached after first call. """ # On POSIX we don't want to cache the ppid as it may unexpectedly # change to 1 (init) in case this process turns into a zombie: # https://github.com/giampaolo/psutil/issues/321 # http://stackoverflow.com/questions/356722/ # XXX should we check creation time here rather than in # Process.parent()? if POSIX: return self._proc.ppid() else: # pragma: no cover self._ppid = self._ppid or self._proc.ppid() return self._ppid def name(self): """The process name. The return value is cached after first call.""" # Process name is only cached on Windows as on POSIX it may # change, see: # https://github.com/giampaolo/psutil/issues/692 if WINDOWS and self._name is not None: return self._name name = self._proc.name() if POSIX and len(name) >= 15: # On UNIX the name gets truncated to the first 15 characters. # If it matches the first part of the cmdline we return that # one instead because it's usually more explicative. # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon". try: cmdline = self.cmdline() except (AccessDenied, ZombieProcess): # Just pass and return the truncated name: it's better # than nothing. Note: there are actual cases where a # zombie process can return a name() but not a # cmdline(), see: # https://github.com/giampaolo/psutil/issues/2239 pass else: if cmdline: extended_name = os.path.basename(cmdline[0]) if extended_name.startswith(name): name = extended_name self._name = name self._proc._name = name return name def exe(self): """The process executable as an absolute path. May also be an empty string. The return value is cached after first call. """ def guess_it(fallback): # try to guess exe from cmdline[0] in absence of a native # exe representation cmdline = self.cmdline() if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'): exe = cmdline[0] # the possible exe # Attempt to guess only in case of an absolute path. # It is not safe otherwise as the process might have # changed cwd. if (os.path.isabs(exe) and os.path.isfile(exe) and os.access(exe, os.X_OK)): return exe if isinstance(fallback, AccessDenied): raise fallback return fallback if self._exe is None: try: exe = self._proc.exe() except AccessDenied as err: return guess_it(fallback=err) else: if not exe: # underlying implementation can legitimately return an # empty string; if that's the case we don't want to # raise AD while guessing from the cmdline try: exe = guess_it(fallback=exe) except AccessDenied: pass self._exe = exe return self._exe def cmdline(self): """The command line this process has been called with.""" return self._proc.cmdline() def status(self): """The process current status as a STATUS_* constant.""" try: return self._proc.status() except ZombieProcess: return STATUS_ZOMBIE def username(self): """The name of the user that owns the process. On UNIX this is calculated by using *real* process uid. """ if POSIX: if pwd is None: # might happen if python was installed from sources raise ImportError( "requires pwd module shipped with standard python") real_uid = self.uids().real try: return pwd.getpwuid(real_uid).pw_name except KeyError: # the uid can't be resolved by the system return str(real_uid) else: return self._proc.username() def create_time(self): """The process creation time as a floating point number expressed in seconds since the epoch. The return value is cached after first call. """ if self._create_time is None: self._create_time = self._proc.create_time() return self._create_time def cwd(self): """Process current working directory as an absolute path.""" return self._proc.cwd() def nice(self, value=None): """Get or set process niceness (priority).""" if value is None: return self._proc.nice_get() else: if not self.is_running(): raise NoSuchProcess(self.pid, self._name) self._proc.nice_set(value) if POSIX: @memoize_when_activated def uids(self): """Return process UIDs as a (real, effective, saved) namedtuple. """ return self._proc.uids() def gids(self): """Return process GIDs as a (real, effective, saved) namedtuple. """ return self._proc.gids() def terminal(self): """The terminal associated with this process, if any, else None. """ return self._proc.terminal() def num_fds(self): """Return the number of file descriptors opened by this process (POSIX only). """ return self._proc.num_fds() # Linux, BSD, AIX and Windows only if hasattr(_psplatform.Process, "io_counters"): def io_counters(self): """Return process I/O statistics as a (read_count, write_count, read_bytes, write_bytes) namedtuple. Those are the number of read/write calls performed and the amount of bytes read and written by the process. """ return self._proc.io_counters() # Linux and Windows if hasattr(_psplatform.Process, "ionice_get"): def ionice(self, ioclass=None, value=None): """Get or set process I/O niceness (priority). On Linux *ioclass* is one of the IOPRIO_CLASS_* constants. *value* is a number which goes from 0 to 7. The higher the value, the lower the I/O priority of the process. On Windows only *ioclass* is used and it can be set to 2 (normal), 1 (low) or 0 (very low). Available on Linux and Windows > Vista only. """ if ioclass is None: if value is not None: raise ValueError("'ioclass' argument must be specified") return self._proc.ionice_get() else: return self._proc.ionice_set(ioclass, value) # Linux / FreeBSD only if hasattr(_psplatform.Process, "rlimit"): def rlimit(self, resource, limits=None): """Get or set process resource limits as a (soft, hard) tuple. *resource* is one of the RLIMIT_* constants. *limits* is supposed to be a (soft, hard) tuple. See "man prlimit" for further info. Available on Linux and FreeBSD only. """ return self._proc.rlimit(resource, limits) # Windows, Linux and FreeBSD only if hasattr(_psplatform.Process, "cpu_affinity_get"): def cpu_affinity(self, cpus=None): """Get or set process CPU affinity. If specified, *cpus* must be a list of CPUs for which you want to set the affinity (e.g. [0, 1]). If an empty list is passed, all egible CPUs are assumed (and set). (Windows, Linux and BSD only). """ if cpus is None: return sorted(set(self._proc.cpu_affinity_get())) else: if not cpus: if hasattr(self._proc, "_get_eligible_cpus"): cpus = self._proc._get_eligible_cpus() else: cpus = tuple(range(len(cpu_times(percpu=True)))) self._proc.cpu_affinity_set(list(set(cpus))) # Linux, FreeBSD, SunOS if hasattr(_psplatform.Process, "cpu_num"): def cpu_num(self): """Return what CPU this process is currently running on. The returned number should be <= psutil.cpu_count() and <= len(psutil.cpu_percent(percpu=True)). It may be used in conjunction with psutil.cpu_percent(percpu=True) to observe the system workload distributed across CPUs. """ return self._proc.cpu_num() # All platforms has it, but maybe not in the future. if hasattr(_psplatform.Process, "environ"): def environ(self): """The environment variables of the process as a dict. Note: this might not reflect changes made after the process started. """ return self._proc.environ() if WINDOWS: def num_handles(self): """Return the number of handles opened by this process (Windows only). """ return self._proc.num_handles() def num_ctx_switches(self): """Return the number of voluntary and involuntary context switches performed by this process. """ return self._proc.num_ctx_switches() def num_threads(self): """Return the number of threads used by this process.""" return self._proc.num_threads() if hasattr(_psplatform.Process, "threads"): def threads(self): """Return threads opened by process as a list of (id, user_time, system_time) namedtuples representing thread id and thread CPU times (user/system). On OpenBSD this method requires root access. """ return self._proc.threads() @_assert_pid_not_reused def children(self, recursive=False): """Return the children of this process as a list of Process instances, pre-emptively checking whether PID has been reused. If *recursive* is True return all the parent descendants. Example (A == this process): A ─┐ │ ├─ B (child) ─┐ │ └─ X (grandchild) ─┐ │ └─ Y (great grandchild) ├─ C (child) └─ D (child) >>> import psutil >>> p = psutil.Process() >>> p.children() B, C, D >>> p.children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be listed as the reference to process A is lost. """ ppid_map = _ppid_map() ret = [] if not recursive: for pid, ppid in ppid_map.items(): if ppid == self.pid: try: child = Process(pid) # if child happens to be older than its parent # (self) it means child's PID has been reused if self.create_time() <= child.create_time(): ret.append(child) except (NoSuchProcess, ZombieProcess): pass else: # Construct a {pid: [child pids]} dict reverse_ppid_map = collections.defaultdict(list) for pid, ppid in ppid_map.items(): reverse_ppid_map[ppid].append(pid) # Recursively traverse that dict, starting from self.pid, # such that we only call Process() on actual children seen = set() stack = [self.pid] while stack: pid = stack.pop() if pid in seen: # Since pids can be reused while the ppid_map is # constructed, there may be rare instances where # there's a cycle in the recorded process "tree". continue seen.add(pid) for child_pid in reverse_ppid_map[pid]: try: child = Process(child_pid) # if child happens to be older than its parent # (self) it means child's PID has been reused intime = self.create_time() <= child.create_time() if intime: ret.append(child) stack.append(child_pid) except (NoSuchProcess, ZombieProcess): pass return ret def cpu_percent(self, interval=None): """Return a float representing the current process CPU utilization as a percentage. When *interval* is 0.0 or None (default) compares process times to system CPU times elapsed since last call, returning immediately (non-blocking). That means that the first time this is called it will return a meaningful 0.0 value. When *interval* is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. A value > 100.0 can be returned in case of processes running multiple threads on different CPU cores. The returned value is explicitly NOT split evenly between all available logical CPUs. This means that a busy loop process running on a system with 2 logical CPUs will be reported as having 100% CPU utilization instead of 50%. Examples: >>> import psutil >>> p = psutil.Process(os.getpid()) >>> # blocking >>> p.cpu_percent(interval=1) 2.0 >>> # non-blocking (percentage since last call) >>> p.cpu_percent(interval=None) 2.9 >>> """ blocking = interval is not None and interval > 0.0 if interval is not None and interval < 0: raise ValueError("interval is not positive (got %r)" % interval) num_cpus = cpu_count() or 1 def timer(): return _timer() * num_cpus if blocking: st1 = timer() pt1 = self._proc.cpu_times() time.sleep(interval) st2 = timer() pt2 = self._proc.cpu_times() else: st1 = self._last_sys_cpu_times pt1 = self._last_proc_cpu_times st2 = timer() pt2 = self._proc.cpu_times() if st1 is None or pt1 is None: self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 return 0.0 delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system) delta_time = st2 - st1 # reset values for next call in case of interval == None self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 try: # This is the utilization split evenly between all CPUs. # E.g. a busy loop process on a 2-CPU-cores system at this # point is reported as 50% instead of 100%. overall_cpus_percent = ((delta_proc / delta_time) * 100) except ZeroDivisionError: # interval was too low return 0.0 else: # Note 1: # in order to emulate "top" we multiply the value for the num # of CPU cores. This way the busy process will be reported as # having 100% (or more) usage. # # Note 2: # taskmgr.exe on Windows differs in that it will show 50% # instead. # # Note 3: # a percentage > 100 is legitimate as it can result from a # process with multiple threads running on different CPU # cores (top does the same), see: # http://stackoverflow.com/questions/1032357 # https://github.com/giampaolo/psutil/issues/474 single_cpu_percent = overall_cpus_percent * num_cpus return round(single_cpu_percent, 1) @memoize_when_activated def cpu_times(self): """Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds. This is similar to os.times() but per-process. On macOS and Windows children_user and children_system are always set to 0. """ return self._proc.cpu_times() @memoize_when_activated def memory_info(self): """Return a namedtuple with variable fields depending on the platform, representing memory information about the process. The "portable" fields available on all platforms are `rss` and `vms`. All numbers are expressed in bytes. """ return self._proc.memory_info() @_common.deprecated_method(replacement="memory_info") def memory_info_ex(self): return self.memory_info() def memory_full_info(self): """This method returns the same information as memory_info(), plus, on some platform (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better representation of actual process memory usage. Namely USS is the memory which is unique to a process and which would be freed if the process was terminated right now. It does so by passing through the whole process address. As such it usually requires higher user privileges than memory_info() and is considerably slower. """ return self._proc.memory_full_info() def memory_percent(self, memtype="rss"): """Compare process memory to total physical system memory and calculate process memory utilization as a percentage. *memtype* argument is a string that dictates what type of process memory you want to compare against (defaults to "rss"). The list of available strings can be obtained like this: >>> psutil.Process().memory_info()._fields ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss') """ valid_types = list(_psplatform.pfullmem._fields) if memtype not in valid_types: raise ValueError("invalid memtype %r; valid types are %r" % ( memtype, tuple(valid_types))) fun = self.memory_info if memtype in _psplatform.pmem._fields else \ self.memory_full_info metrics = fun() value = getattr(metrics, memtype) # use cached value if available total_phymem = _TOTAL_PHYMEM or virtual_memory().total if not total_phymem > 0: # we should never get here raise ValueError( "can't calculate process memory percent because " "total physical system memory is not positive (%r)" % total_phymem) return (value / float(total_phymem)) * 100 if hasattr(_psplatform.Process, "memory_maps"): def memory_maps(self, grouped=True): """Return process' mapped memory regions as a list of namedtuples whose fields are variable depending on the platform. If *grouped* is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If *grouped* is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms'). """ it = self._proc.memory_maps() if grouped: d = {} for tupl in it: path = tupl[2] nums = tupl[3:] try: d[path] = map(lambda x, y: x + y, d[path], nums) except KeyError: d[path] = nums nt = _psplatform.pmmap_grouped return [nt(path, *d[path]) for path in d] # NOQA else: nt = _psplatform.pmmap_ext return [nt(*x) for x in it] def open_files(self): """Return files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number. """ return self._proc.open_files() def connections(self, kind='inet'): """Return socket connections opened by process as a list of (fd, family, type, laddr, raddr, status) namedtuples. The *kind* parameter filters for connections that match the following criteria: +------------+----------------------------------------------------+ | Kind Value | Connections using | +------------+----------------------------------------------------+ | inet | IPv4 and IPv6 | | inet4 | IPv4 | | inet6 | IPv6 | | tcp | TCP | | tcp4 | TCP over IPv4 | | tcp6 | TCP over IPv6 | | udp | UDP | | udp4 | UDP over IPv4 | | udp6 | UDP over IPv6 | | unix | UNIX socket (both UDP and TCP protocols) | | all | the sum of all the possible families and protocols | +------------+----------------------------------------------------+ """ return self._proc.connections(kind) # --- signals if POSIX: def _send_signal(self, sig): assert not self.pid < 0, self.pid if self.pid == 0: # see "man 2 kill" raise ValueError( "preventing sending signal to process with PID 0 as it " "would affect every process in the process group of the " "calling process (os.getpid()) instead of PID 0") try: os.kill(self.pid, sig) except ProcessLookupError: if OPENBSD and pid_exists(self.pid): # We do this because os.kill() lies in case of # zombie processes. raise ZombieProcess(self.pid, self._name, self._ppid) else: self._gone = True raise NoSuchProcess(self.pid, self._name) except PermissionError: raise AccessDenied(self.pid, self._name) @_assert_pid_not_reused def send_signal(self, sig): """Send a signal *sig* to process pre-emptively checking whether PID has been reused (see signal module constants) . On Windows only SIGTERM is valid and is treated as an alias for kill(). """ if POSIX: self._send_signal(sig) else: # pragma: no cover self._proc.send_signal(sig) @_assert_pid_not_reused def suspend(self): """Suspend process execution with SIGSTOP pre-emptively checking whether PID has been reused. On Windows this has the effect of suspending all process threads. """ if POSIX: self._send_signal(signal.SIGSTOP) else: # pragma: no cover self._proc.suspend() @_assert_pid_not_reused def resume(self): """Resume process execution with SIGCONT pre-emptively checking whether PID has been reused. On Windows this has the effect of resuming all process threads. """ if POSIX: self._send_signal(signal.SIGCONT) else: # pragma: no cover self._proc.resume() @_assert_pid_not_reused def terminate(self): """Terminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). """ if POSIX: self._send_signal(signal.SIGTERM) else: # pragma: no cover self._proc.kill() @_assert_pid_not_reused def kill(self): """Kill the current process with SIGKILL pre-emptively checking whether PID has been reused. """ if POSIX: self._send_signal(signal.SIGKILL) else: # pragma: no cover self._proc.kill() def wait(self, timeout=None): """Wait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. On Windows there's no such limitation (exit code is always returned). If the process is already terminated immediately return None instead of raising NoSuchProcess. If *timeout* (in seconds) is specified and process is still alive raise TimeoutExpired. To wait for multiple Process(es) use psutil.wait_procs(). """ if timeout is not None and not timeout >= 0: raise ValueError("timeout must be a positive integer") if self._exitcode is not _SENTINEL: return self._exitcode self._exitcode = self._proc.wait(timeout) return self._exitcode # The valid attr names which can be processed by Process.as_dict(). _as_dict_attrnames = set( [x for x in dir(Process) if not x.startswith('_') and x not in ['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', 'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit', 'memory_info_ex', 'oneshot']]) # ===================================================================== # --- Popen class # ===================================================================== class Popen(Process): """Same as subprocess.Popen, but in addition it provides all psutil.Process methods in a single class. For the following methods which are common to both classes, psutil implementation takes precedence: * send_signal() * terminate() * kill() This is done in order to avoid killing another process in case its PID has been reused, fixing BPO-6973. >>> import psutil >>> from subprocess import PIPE >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE) >>> p.name() 'python' >>> p.uids() user(real=1000, effective=1000, saved=1000) >>> p.username() 'giampaolo' >>> p.communicate() ('hi\n', None) >>> p.terminate() >>> p.wait(timeout=2) 0 >>> """ def __init__(self, *args, **kwargs): # Explicitly avoid to raise NoSuchProcess in case the process # spawned by subprocess.Popen terminates too quickly, see: # https://github.com/giampaolo/psutil/issues/193 self.__subproc = subprocess.Popen(*args, **kwargs) self._init(self.__subproc.pid, _ignore_nsp=True) def __dir__(self): return sorted(set(dir(Popen) + dir(subprocess.Popen))) def __enter__(self): if hasattr(self.__subproc, '__enter__'): self.__subproc.__enter__() return self def __exit__(self, *args, **kwargs): if hasattr(self.__subproc, '__exit__'): return self.__subproc.__exit__(*args, **kwargs) else: if self.stdout: self.stdout.close() if self.stderr: self.stderr.close() try: # Flushing a BufferedWriter may raise an error. if self.stdin: self.stdin.close() finally: # Wait for the process to terminate, to avoid zombies. self.wait() def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: try: return object.__getattribute__(self.__subproc, name) except AttributeError: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def wait(self, timeout=None): if self.__subproc.returncode is not None: return self.__subproc.returncode ret = super(Popen, self).wait(timeout) self.__subproc.returncode = ret return ret # ===================================================================== # --- system processes related functions # ===================================================================== def pids(): """Return a list of current running PIDs.""" global _LOWEST_PID ret = sorted(_psplatform.pids()) _LOWEST_PID = ret[0] return ret def pid_exists(pid): """Return True if given PID exists in the current process list. This is faster than doing "pid in psutil.pids()" and should be preferred. """ if pid < 0: return False elif pid == 0 and POSIX: # On POSIX we use os.kill() to determine PID existence. # According to "man 2 kill" PID 0 has a special meaning # though: it refers to <<every process in the process # group of the calling process>> and that is not we want # to do here. return pid in pids() else: return _psplatform.pid_exists(pid) _pmap = {} def process_iter(attrs=None, ad_value=None): """Return a generator yielding a Process instance for all running processes. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. Cached Process instances are checked for identity so that you're safe in case a PID has been reused by another process, in which case the cached instance is updated. The sorting order in which processes are yielded is based on their PIDs. *attrs* and *ad_value* have the same meaning as in Process.as_dict(). If *attrs* is specified as_dict() is called and the resulting dict is stored as a 'info' attribute attached to returned Process instance. If *attrs* is an empty list it will retrieve all process info (slow). """ global _pmap def add(pid): proc = Process(pid) if attrs is not None: proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value) pmap[proc.pid] = proc return proc def remove(pid): pmap.pop(pid, None) pmap = _pmap.copy() a = set(pids()) b = set(pmap.keys()) new_pids = a - b gone_pids = b - a for pid in gone_pids: remove(pid) try: ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items())) for pid, proc in ls: try: if proc is None: # new process yield add(pid) else: # use is_running() to check whether PID has been # reused by another process in which case yield a # new Process instance if proc.is_running(): if attrs is not None: proc.info = proc.as_dict( attrs=attrs, ad_value=ad_value) yield proc else: yield add(pid) except NoSuchProcess: remove(pid) except AccessDenied: # Process creation time can't be determined hence there's # no way to tell whether the pid of the cached process # has been reused. Just return the cached version. if proc is None and pid in pmap: try: yield pmap[pid] except KeyError: # If we get here it is likely that 2 threads were # using process_iter(). pass else: raise finally: _pmap = pmap def wait_procs(procs, timeout=None, callback=None): """Convenience function which waits for a list of processes to terminate. Return a (gone, alive) tuple indicating which processes are gone and which ones are still alive. The gone ones will have a new *returncode* attribute indicating process exit status (may be None). *callback* is a function which gets called every time a process terminates (a Process instance is passed as callback argument). Function will return as soon as all processes terminate or when *timeout* occurs. Differently from Process.wait() it will not raise TimeoutExpired if *timeout* occurs. Typical use case is: - send SIGTERM to a list of processes - give them some time to terminate - send SIGKILL to those ones which are still alive Example: >>> def on_terminate(proc): ... print("process {} terminated".format(proc)) ... >>> for p in procs: ... p.terminate() ... >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate) >>> for p in alive: ... p.kill() """ def check_gone(proc, timeout): try: returncode = proc.wait(timeout=timeout) except TimeoutExpired: pass except _SubprocessTimeoutExpired: pass else: if returncode is not None or not proc.is_running(): # Set new Process instance attribute. proc.returncode = returncode gone.add(proc) if callback is not None: callback(proc) if timeout is not None and not timeout >= 0: msg = "timeout must be a positive integer, got %s" % timeout raise ValueError(msg) gone = set() alive = set(procs) if callback is not None and not callable(callback): raise TypeError("callback %r is not a callable" % callable) if timeout is not None: deadline = _timer() + timeout while alive: if timeout is not None and timeout <= 0: break for proc in alive: # Make sure that every complete iteration (all processes) # will last max 1 sec. # We do this because we don't want to wait too long on a # single process: in case it terminates too late other # processes may disappear in the meantime and their PID # reused. max_timeout = 1.0 / len(alive) if timeout is not None: timeout = min((deadline - _timer()), max_timeout) if timeout <= 0: break check_gone(proc, timeout) else: check_gone(proc, max_timeout) alive = alive - gone if alive: # Last attempt over processes survived so far. # timeout == 0 won't make this function wait any further. for proc in alive: check_gone(proc, 0) alive = alive - gone return (list(gone), list(alive)) # ===================================================================== # --- CPU related functions # ===================================================================== def cpu_count(logical=True): """Return the number of logical CPUs in the system (same as os.cpu_count() in Python 3.4). If *logical* is False return the number of physical cores only (e.g. hyper thread CPUs are excluded). Return None if undetermined. The return value is cached after first call. If desired cache can be cleared like this: >>> psutil.cpu_count.cache_clear() """ if logical: ret = _psplatform.cpu_count_logical() else: ret = _psplatform.cpu_count_cores() if ret is not None and ret < 1: ret = None return ret def cpu_times(percpu=False): """Return system-wide CPU times as a namedtuple. Every CPU time represents the seconds the CPU has spent in the given mode. The namedtuple's fields availability varies depending on the platform: - user - system - idle - nice (UNIX) - iowait (Linux) - irq (Linux, FreeBSD) - softirq (Linux) - steal (Linux >= 2.6.11) - guest (Linux >= 2.6.24) - guest_nice (Linux >= 3.2.0) When *percpu* is True return a list of namedtuples for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. """ if not percpu: return _psplatform.cpu_times() else: return _psplatform.per_cpu_times() try: _last_cpu_times = cpu_times() except Exception: # Don't want to crash at import time. _last_cpu_times = None try: _last_per_cpu_times = cpu_times(percpu=True) except Exception: # Don't want to crash at import time. _last_per_cpu_times = None def _cpu_tot_time(times): """Given a cpu_time() ntuple calculates the total CPU time (including idle time). """ tot = sum(times) if LINUX: # On Linux guest times are already accounted in "user" or # "nice" times, so we subtract them from total. # Htop does the same. References: # https://github.com/giampaolo/psutil/pull/940 # http://unix.stackexchange.com/questions/178045 # https://github.com/torvalds/linux/blob/ # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/ # cputime.c#L158 tot -= getattr(times, "guest", 0) # Linux 2.6.24+ tot -= getattr(times, "guest_nice", 0) # Linux 3.2.0+ return tot def _cpu_busy_time(times): """Given a cpu_time() ntuple calculates the busy CPU time. We do so by subtracting all idle CPU times. """ busy = _cpu_tot_time(times) busy -= times.idle # Linux: "iowait" is time during which the CPU does not do anything # (waits for IO to complete). On Linux IO wait is *not* accounted # in "idle" time so we subtract it. Htop does the same. # References: # https://github.com/torvalds/linux/blob/ # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244 busy -= getattr(times, "iowait", 0) return busy def _cpu_times_deltas(t1, t2): assert t1._fields == t2._fields, (t1, t2) field_deltas = [] for field in _psplatform.scputimes._fields: field_delta = getattr(t2, field) - getattr(t1, field) # CPU times are always supposed to increase over time # or at least remain the same and that's because time # cannot go backwards. # Surprisingly sometimes this might not be the case (at # least on Windows and Linux), see: # https://github.com/giampaolo/psutil/issues/392 # https://github.com/giampaolo/psutil/issues/645 # https://github.com/giampaolo/psutil/issues/1210 # Trim negative deltas to zero to ignore decreasing fields. # top does the same. Reference: # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063 field_delta = max(0, field_delta) field_deltas.append(field_delta) return _psplatform.scputimes(*field_deltas) def cpu_percent(interval=None, percpu=False): """Return a float representing the current system-wide CPU utilization as a percentage. When *interval* is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When *interval* is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately (non blocking). That means the first time this is called it will return a meaningless 0.0 value which you should ignore. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When *percpu* is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. Examples: >>> # blocking, system-wide >>> psutil.cpu_percent(interval=1) 2.0 >>> >>> # blocking, per-cpu >>> psutil.cpu_percent(interval=1, percpu=True) [2.0, 1.0] >>> >>> # non-blocking (percentage since last call) >>> psutil.cpu_percent(interval=None) 2.9 >>> """ global _last_cpu_times global _last_per_cpu_times blocking = interval is not None and interval > 0.0 if interval is not None and interval < 0: raise ValueError("interval is not positive (got %r)" % interval) def calculate(t1, t2): times_delta = _cpu_times_deltas(t1, t2) all_delta = _cpu_tot_time(times_delta) busy_delta = _cpu_busy_time(times_delta) try: busy_perc = (busy_delta / all_delta) * 100 except ZeroDivisionError: return 0.0 else: return round(busy_perc, 1) # system-wide usage if not percpu: if blocking: t1 = cpu_times() time.sleep(interval) else: t1 = _last_cpu_times if t1 is None: # Something bad happened at import time. We'll # get a meaningful result on the next call. See: # https://github.com/giampaolo/psutil/pull/715 t1 = cpu_times() _last_cpu_times = cpu_times() return calculate(t1, _last_cpu_times) # per-cpu usage else: ret = [] if blocking: tot1 = cpu_times(percpu=True) time.sleep(interval) else: tot1 = _last_per_cpu_times if tot1 is None: # Something bad happened at import time. We'll # get a meaningful result on the next call. See: # https://github.com/giampaolo/psutil/pull/715 tot1 = cpu_times(percpu=True) _last_per_cpu_times = cpu_times(percpu=True) for t1, t2 in zip(tot1, _last_per_cpu_times): ret.append(calculate(t1, t2)) return ret # Use separate global vars for cpu_times_percent() so that it's # independent from cpu_percent() and they can both be used within # the same program. _last_cpu_times_2 = _last_cpu_times _last_per_cpu_times_2 = _last_per_cpu_times def cpu_times_percent(interval=None, percpu=False): """Same as cpu_percent() but provides utilization percentages for each specific CPU time as is returned by cpu_times(). For instance, on Linux we'll get: >>> cpu_times_percent() cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) >>> *interval* and *percpu* arguments have the same meaning as in cpu_percent(). """ global _last_cpu_times_2 global _last_per_cpu_times_2 blocking = interval is not None and interval > 0.0 if interval is not None and interval < 0: raise ValueError("interval is not positive (got %r)" % interval) def calculate(t1, t2): nums = [] times_delta = _cpu_times_deltas(t1, t2) all_delta = _cpu_tot_time(times_delta) # "scale" is the value to multiply each delta with to get percentages. # We use "max" to avoid division by zero (if all_delta is 0, then all # fields are 0 so percentages will be 0 too. all_delta cannot be a # fraction because cpu times are integers) scale = 100.0 / max(1, all_delta) for field_delta in times_delta: field_perc = field_delta * scale field_perc = round(field_perc, 1) # make sure we don't return negative values or values over 100% field_perc = min(max(0.0, field_perc), 100.0) nums.append(field_perc) return _psplatform.scputimes(*nums) # system-wide usage if not percpu: if blocking: t1 = cpu_times() time.sleep(interval) else: t1 = _last_cpu_times_2 if t1 is None: # Something bad happened at import time. We'll # get a meaningful result on the next call. See: # https://github.com/giampaolo/psutil/pull/715 t1 = cpu_times() _last_cpu_times_2 = cpu_times() return calculate(t1, _last_cpu_times_2) # per-cpu usage else: ret = [] if blocking: tot1 = cpu_times(percpu=True) time.sleep(interval) else: tot1 = _last_per_cpu_times_2 if tot1 is None: # Something bad happened at import time. We'll # get a meaningful result on the next call. See: # https://github.com/giampaolo/psutil/pull/715 tot1 = cpu_times(percpu=True) _last_per_cpu_times_2 = cpu_times(percpu=True) for t1, t2 in zip(tot1, _last_per_cpu_times_2): ret.append(calculate(t1, t2)) return ret def cpu_stats(): """Return CPU statistics.""" return _psplatform.cpu_stats() if hasattr(_psplatform, "cpu_freq"): def cpu_freq(percpu=False): """Return CPU frequency as a namedtuple including current, min and max frequency expressed in Mhz. If *percpu* is True and the system supports per-cpu frequency retrieval (Linux only) a list of frequencies is returned for each CPU. If not a list with one element is returned. """ ret = _psplatform.cpu_freq() if percpu: return ret else: num_cpus = float(len(ret)) if num_cpus == 0: return None elif num_cpus == 1: return ret[0] else: currs, mins, maxs = 0.0, 0.0, 0.0 set_none = False for cpu in ret: currs += cpu.current # On Linux if /proc/cpuinfo is used min/max are set # to None. if LINUX and cpu.min is None: set_none = True continue mins += cpu.min maxs += cpu.max current = currs / num_cpus if set_none: min_ = max_ = None else: min_ = mins / num_cpus max_ = maxs / num_cpus return _common.scpufreq(current, min_, max_) __all__.append("cpu_freq") if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"): # Perform this hasattr check once on import time to either use the # platform based code or proxy straight from the os module. if hasattr(os, "getloadavg"): getloadavg = os.getloadavg else: getloadavg = _psplatform.getloadavg __all__.append("getloadavg") # ===================================================================== # --- system memory related functions # ===================================================================== def virtual_memory(): """Return statistics about system memory usage as a namedtuple including the following fields, expressed in bytes: - total: total physical memory available. - available: the memory that can be given instantly to processes without the system going into swap. This is calculated by summing different memory values depending on the platform and it is supposed to be used to monitor actual memory usage in a cross platform fashion. - percent: the percentage usage calculated as (total - available) / total * 100 - used: memory used, calculated differently depending on the platform and designed for informational purposes only: macOS: active + wired BSD: active + wired + cached Linux: total - free - free: memory not being used at all (zeroed) that is readily available; note that this doesn't reflect the actual memory available (use 'available' instead) Platform-specific fields: - active (UNIX): memory currently in use or very recently used, and so it is in RAM. - inactive (UNIX): memory that is marked as not used. - buffers (BSD, Linux): cache for things like file system metadata. - cached (BSD, macOS): cache for various things. - wired (macOS, BSD): memory that is marked to always stay in RAM. It is never moved to disk. - shared (BSD): memory that may be simultaneously accessed by multiple processes. The sum of 'used' and 'available' does not necessarily equal total. On Windows 'available' and 'free' are the same. """ global _TOTAL_PHYMEM ret = _psplatform.virtual_memory() # cached for later use in Process.memory_percent() _TOTAL_PHYMEM = ret.total return ret def swap_memory(): """Return system swap memory statistics as a namedtuple including the following fields: - total: total swap memory in bytes - used: used swap memory in bytes - free: free swap memory in bytes - percent: the percentage usage - sin: no. of bytes the system has swapped in from disk (cumulative) - sout: no. of bytes the system has swapped out from disk (cumulative) 'sin' and 'sout' on Windows are meaningless and always set to 0. """ return _psplatform.swap_memory() # ===================================================================== # --- disks/paritions related functions # ===================================================================== def disk_usage(path): """Return disk usage statistics about the given *path* as a namedtuple including total, used and free space expressed in bytes plus the percentage usage. """ return _psplatform.disk_usage(path) def disk_partitions(all=False): """Return mounted partitions as a list of (device, mountpoint, fstype, opts) namedtuple. 'opts' field is a raw string separated by commas indicating mount options which may vary depending on the platform. If *all* parameter is False return physical devices only and ignore all others. """ def pathconf(path, name): try: return os.pathconf(path, name) except (OSError, AttributeError): pass ret = _psplatform.disk_partitions(all) if POSIX: new = [] for item in ret: nt = item._replace( maxfile=pathconf(item.mountpoint, 'PC_NAME_MAX'), maxpath=pathconf(item.mountpoint, 'PC_PATH_MAX')) new.append(nt) return new else: return ret def disk_io_counters(perdisk=False, nowrap=True): """Return system disk I/O statistics as a namedtuple including the following fields: - read_count: number of reads - write_count: number of writes - read_bytes: number of bytes read - write_bytes: number of bytes written - read_time: time spent reading from disk (in ms) - write_time: time spent writing to disk (in ms) Platform specific: - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms) - read_merged_count (Linux): number of merged reads - write_merged_count (Linux): number of merged writes If *perdisk* is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the namedtuple described above as the values. If *nowrap* is True it detects and adjust the numbers which overflow and wrap (restart from 0) and add "old value" to "new value" so that the returned numbers will always be increasing or remain the same, but never decrease. "disk_io_counters.cache_clear()" can be used to invalidate the cache. On recent Windows versions 'diskperf -y' command may need to be executed first otherwise this function won't find any disk. """ kwargs = dict(perdisk=perdisk) if LINUX else {} rawdict = _psplatform.disk_io_counters(**kwargs) if not rawdict: return {} if perdisk else None if nowrap: rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters') nt = getattr(_psplatform, "sdiskio", _common.sdiskio) if perdisk: for disk, fields in rawdict.items(): rawdict[disk] = nt(*fields) return rawdict else: return nt(*(sum(x) for x in zip(*rawdict.values()))) disk_io_counters.cache_clear = functools.partial( _wrap_numbers.cache_clear, 'psutil.disk_io_counters') disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache" # ===================================================================== # --- network related functions # ===================================================================== def net_io_counters(pernic=False, nowrap=True): """Return network I/O statistics as a namedtuple including the following fields: - bytes_sent: number of bytes sent - bytes_recv: number of bytes received - packets_sent: number of packets sent - packets_recv: number of packets received - errin: total number of errors while receiving - errout: total number of errors while sending - dropin: total number of incoming packets which were dropped - dropout: total number of outgoing packets which were dropped (always 0 on macOS and BSD) If *pernic* is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values. If *nowrap* is True it detects and adjust the numbers which overflow and wrap (restart from 0) and add "old value" to "new value" so that the returned numbers will always be increasing or remain the same, but never decrease. "disk_io_counters.cache_clear()" can be used to invalidate the cache. """ rawdict = _psplatform.net_io_counters() if not rawdict: return {} if pernic else None if nowrap: rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters') if pernic: for nic, fields in rawdict.items(): rawdict[nic] = _common.snetio(*fields) return rawdict else: return _common.snetio(*[sum(x) for x in zip(*rawdict.values())]) net_io_counters.cache_clear = functools.partial( _wrap_numbers.cache_clear, 'psutil.net_io_counters') net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache" def net_connections(kind='inet'): """Return system-wide socket connections as a list of (fd, family, type, laddr, raddr, status, pid) namedtuples. In case of limited privileges 'fd' and 'pid' may be set to -1 and None respectively. The *kind* parameter filters for connections that fit the following criteria: +------------+----------------------------------------------------+ | Kind Value | Connections using | +------------+----------------------------------------------------+ | inet | IPv4 and IPv6 | | inet4 | IPv4 | | inet6 | IPv6 | | tcp | TCP | | tcp4 | TCP over IPv4 | | tcp6 | TCP over IPv6 | | udp | UDP | | udp4 | UDP over IPv4 | | udp6 | UDP over IPv6 | | unix | UNIX socket (both UDP and TCP protocols) | | all | the sum of all the possible families and protocols | +------------+----------------------------------------------------+ On macOS this function requires root privileges. """ return _psplatform.net_connections(kind) def net_if_addrs(): """Return the addresses associated to each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a list of namedtuples for each address assigned to the NIC. Each namedtuple includes 5 fields: - family: can be either socket.AF_INET, socket.AF_INET6 or psutil.AF_LINK, which refers to a MAC address. - address: is the primary address and it is always set. - netmask: and 'broadcast' and 'ptp' may be None. - ptp: stands for "point to point" and references the destination address on a point to point interface (typically a VPN). - broadcast: and *ptp* are mutually exclusive. Note: you can have more than one address of the same family associated with each interface. """ has_enums = sys.version_info >= (3, 4) if has_enums: import socket rawlist = _psplatform.net_if_addrs() rawlist.sort(key=lambda x: x[1]) # sort by family ret = collections.defaultdict(list) for name, fam, addr, mask, broadcast, ptp in rawlist: if has_enums: try: fam = socket.AddressFamily(fam) except ValueError: if WINDOWS and fam == -1: fam = _psplatform.AF_LINK elif (hasattr(_psplatform, "AF_LINK") and _psplatform.AF_LINK == fam): # Linux defines AF_LINK as an alias for AF_PACKET. # We re-set the family here so that repr(family) # will show AF_LINK rather than AF_PACKET fam = _psplatform.AF_LINK if fam == _psplatform.AF_LINK: # The underlying C function may return an incomplete MAC # address in which case we fill it with null bytes, see: # https://github.com/giampaolo/psutil/issues/786 separator = ":" if POSIX else "-" while addr.count(separator) < 5: addr += "%s00" % separator ret[name].append(_common.snicaddr(fam, addr, mask, broadcast, ptp)) return dict(ret) def net_if_stats(): """Return information about each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a namedtuple with the following fields: - isup: whether the interface is up (bool) - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or NIC_DUPLEX_UNKNOWN - speed: the NIC speed expressed in mega bits (MB); if it can't be determined (e.g. 'localhost') it will be set to 0. - mtu: the maximum transmission unit expressed in bytes. """ return _psplatform.net_if_stats() # ===================================================================== # --- sensors # ===================================================================== # Linux, macOS if hasattr(_psplatform, "sensors_temperatures"): def sensors_temperatures(fahrenheit=False): """Return hardware temperatures. Each entry is a namedtuple representing a certain hardware sensor (it may be a CPU, an hard disk or something else, depending on the OS and its configuration). All temperatures are expressed in celsius unless *fahrenheit* is set to True. """ def convert(n): if n is not None: return (float(n) * 9 / 5) + 32 if fahrenheit else n ret = collections.defaultdict(list) rawdict = _psplatform.sensors_temperatures() for name, values in rawdict.items(): while values: label, current, high, critical = values.pop(0) current = convert(current) high = convert(high) critical = convert(critical) if high and not critical: critical = high elif critical and not high: high = critical ret[name].append( _common.shwtemp(label, current, high, critical)) return dict(ret) __all__.append("sensors_temperatures") # Linux if hasattr(_psplatform, "sensors_fans"): def sensors_fans(): """Return fans speed. Each entry is a namedtuple representing a certain hardware sensor. All speed are expressed in RPM (rounds per minute). """ return _psplatform.sensors_fans() __all__.append("sensors_fans") # Linux, Windows, FreeBSD, macOS if hasattr(_psplatform, "sensors_battery"): def sensors_battery(): """Return battery information. If no battery is installed returns None. - percent: battery power left as a percentage. - secsleft: a rough approximation of how many seconds are left before the battery runs out of power. May be POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED. - power_plugged: True if the AC power cable is connected. """ return _psplatform.sensors_battery() __all__.append("sensors_battery") # ===================================================================== # --- other system related functions # ===================================================================== def boot_time(): """Return the system boot time expressed in seconds since the epoch.""" # Note: we are not caching this because it is subject to # system clock updates. return _psplatform.boot_time() def users(): """Return users currently connected on the system as a list of namedtuples including the following fields. - user: the name of the user - terminal: the tty or pseudo-tty associated with the user, if any. - host: the host name associated with the entry, if any. - started: the creation time as a floating point number expressed in seconds since the epoch. """ return _psplatform.users() # ===================================================================== # --- Windows services # ===================================================================== if WINDOWS: def win_service_iter(): """Return a generator yielding a WindowsService instance for all Windows services installed. """ return _psplatform.win_service_iter() def win_service_get(name): """Get a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. """ return _psplatform.win_service_get(name) # ===================================================================== def _set_debug(value): """Enable or disable PSUTIL_DEBUG option, which prints debugging messages to stderr. """ import psutil._common psutil._common.PSUTIL_DEBUG = bool(value) _psplatform.cext.set_debug(bool(value)) def test(): # pragma: no cover from ._common import bytes2human from ._compat import get_terminal_size today_day = datetime.date.today() templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s" attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times', 'create_time', 'memory_info', 'status', 'nice', 'username'] print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", # NOQA "STATUS", "START", "TIME", "CMDLINE")) for p in process_iter(attrs, ad_value=None): if p.info['create_time']: ctime = datetime.datetime.fromtimestamp(p.info['create_time']) if ctime.date() == today_day: ctime = ctime.strftime("%H:%M") else: ctime = ctime.strftime("%b%d") else: ctime = '' if p.info['cpu_times']: cputime = time.strftime("%M:%S", time.localtime(sum(p.info['cpu_times']))) else: cputime = '' user = p.info['username'] or '' if not user and POSIX: try: user = p.uids()[0] except Error: pass if user and WINDOWS and '\\' in user: user = user.split('\\')[1] user = user[:9] vms = bytes2human(p.info['memory_info'].vms) if \ p.info['memory_info'] is not None else '' rss = bytes2human(p.info['memory_info'].rss) if \ p.info['memory_info'] is not None else '' memp = round(p.info['memory_percent'], 1) if \ p.info['memory_percent'] is not None else '' nice = int(p.info['nice']) if p.info['nice'] else '' if p.info['cmdline']: cmdline = ' '.join(p.info['cmdline']) else: cmdline = p.info['name'] status = p.info['status'][:5] if p.info['status'] else '' line = templ % ( user[:10], p.info['pid'], memp, vms, rss, nice, status, ctime, cputime, cmdline) print(line[:get_terminal_size()[0]]) # NOQA del memoize_when_activated, division if sys.version_info[0] < 3: del num, x if __name__ == "__main__": test()
87,870
35.086653
79
py
psutil
psutil-master/psutil/_common.py
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Common objects shared by __init__.py and _ps*.py modules.""" # Note: this module is imported by setup.py so it should not import # psutil or third-party modules. 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 sys.version_info >= (3, 4): import enum else: enum = None # can't take it from _common.py as this script is imported by setup.py PY3 = sys.version_info[0] == 3 PSUTIL_DEBUG = bool(os.getenv('PSUTIL_DEBUG')) _DEFAULT = object() __all__ = [ # OS constants 'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'MACOS', 'OSX', 'POSIX', 'SUNOS', 'WINDOWS', # connection constants 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT', # net constants 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', # process status constants 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED', 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL', 'STATUS_WAKING', 'STATUS_ZOMBIE', 'STATUS_PARKED', # other constants 'ENCODING', 'ENCODING_ERRS', 'AF_INET6', # named tuples 'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile', 'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart', 'sdiskusage', 'snetio', 'snicaddr', 'snicstats', 'sswap', 'suser', # utility functions 'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize', 'parse_environ_block', 'path_exists_strict', 'usage_percent', 'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers", 'open_text', 'open_binary', 'cat', 'bcat', 'bytes2human', 'conn_to_ntuple', 'debug', # shell utils 'hilite', 'term_supports_colors', 'print_color', ] # =================================================================== # --- OS constants # =================================================================== POSIX = os.name == "posix" WINDOWS = os.name == "nt" LINUX = sys.platform.startswith("linux") MACOS = sys.platform.startswith("darwin") OSX = MACOS # deprecated alias FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd")) OPENBSD = sys.platform.startswith("openbsd") NETBSD = sys.platform.startswith("netbsd") BSD = FREEBSD or OPENBSD or NETBSD SUNOS = sys.platform.startswith(("sunos", "solaris")) AIX = sys.platform.startswith("aix") # =================================================================== # --- API constants # =================================================================== # Process.status() STATUS_RUNNING = "running" STATUS_SLEEPING = "sleeping" STATUS_DISK_SLEEP = "disk-sleep" STATUS_STOPPED = "stopped" STATUS_TRACING_STOP = "tracing-stop" STATUS_ZOMBIE = "zombie" STATUS_DEAD = "dead" STATUS_WAKE_KILL = "wake-kill" STATUS_WAKING = "waking" STATUS_IDLE = "idle" # Linux, macOS, FreeBSD STATUS_LOCKED = "locked" # FreeBSD STATUS_WAITING = "waiting" # FreeBSD STATUS_SUSPENDED = "suspended" # NetBSD STATUS_PARKED = "parked" # Linux # Process.connections() and psutil.net_connections() CONN_ESTABLISHED = "ESTABLISHED" CONN_SYN_SENT = "SYN_SENT" CONN_SYN_RECV = "SYN_RECV" CONN_FIN_WAIT1 = "FIN_WAIT1" CONN_FIN_WAIT2 = "FIN_WAIT2" CONN_TIME_WAIT = "TIME_WAIT" CONN_CLOSE = "CLOSE" CONN_CLOSE_WAIT = "CLOSE_WAIT" CONN_LAST_ACK = "LAST_ACK" CONN_LISTEN = "LISTEN" CONN_CLOSING = "CLOSING" CONN_NONE = "NONE" # net_if_stats() if enum is None: NIC_DUPLEX_FULL = 2 NIC_DUPLEX_HALF = 1 NIC_DUPLEX_UNKNOWN = 0 else: class NicDuplex(enum.IntEnum): NIC_DUPLEX_FULL = 2 NIC_DUPLEX_HALF = 1 NIC_DUPLEX_UNKNOWN = 0 globals().update(NicDuplex.__members__) # sensors_battery() if enum is None: POWER_TIME_UNKNOWN = -1 POWER_TIME_UNLIMITED = -2 else: class BatteryTime(enum.IntEnum): POWER_TIME_UNKNOWN = -1 POWER_TIME_UNLIMITED = -2 globals().update(BatteryTime.__members__) # --- others ENCODING = sys.getfilesystemencoding() if not PY3: ENCODING_ERRS = "replace" else: try: ENCODING_ERRS = sys.getfilesystemencodeerrors() # py 3.6 except AttributeError: ENCODING_ERRS = "surrogateescape" if POSIX else "replace" # =================================================================== # --- namedtuples # =================================================================== # --- for system functions # psutil.swap_memory() sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin', 'sout']) # psutil.disk_usage() sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent']) # psutil.disk_io_counters() sdiskio = namedtuple('sdiskio', ['read_count', 'write_count', 'read_bytes', 'write_bytes', 'read_time', 'write_time']) # psutil.disk_partitions() sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts', 'maxfile', 'maxpath']) # psutil.net_io_counters() snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv', 'packets_sent', 'packets_recv', 'errin', 'errout', 'dropin', 'dropout']) # psutil.users() suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid']) # psutil.net_connections() sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr', 'status', 'pid']) # psutil.net_if_addrs() snicaddr = namedtuple('snicaddr', ['family', 'address', 'netmask', 'broadcast', 'ptp']) # psutil.net_if_stats() snicstats = namedtuple('snicstats', ['isup', 'duplex', 'speed', 'mtu', 'flags']) # psutil.cpu_stats() scpustats = namedtuple( 'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls']) # psutil.cpu_freq() scpufreq = namedtuple('scpufreq', ['current', 'min', 'max']) # psutil.sensors_temperatures() shwtemp = namedtuple( 'shwtemp', ['label', 'current', 'high', 'critical']) # psutil.sensors_battery() sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged']) # psutil.sensors_fans() sfan = namedtuple('sfan', ['label', 'current']) # --- for Process methods # psutil.Process.cpu_times() pcputimes = namedtuple('pcputimes', ['user', 'system', 'children_user', 'children_system']) # psutil.Process.open_files() popenfile = namedtuple('popenfile', ['path', 'fd']) # psutil.Process.threads() pthread = namedtuple('pthread', ['id', 'user_time', 'system_time']) # psutil.Process.uids() puids = namedtuple('puids', ['real', 'effective', 'saved']) # psutil.Process.gids() pgids = namedtuple('pgids', ['real', 'effective', 'saved']) # psutil.Process.io_counters() pio = namedtuple('pio', ['read_count', 'write_count', 'read_bytes', 'write_bytes']) # psutil.Process.ionice() pionice = namedtuple('pionice', ['ioclass', 'value']) # psutil.Process.ctx_switches() pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary']) # psutil.Process.connections() pconn = namedtuple('pconn', ['fd', 'family', 'type', 'laddr', 'raddr', 'status']) # psutil.connections() and psutil.Process.connections() addr = namedtuple('addr', ['ip', 'port']) # =================================================================== # --- Process.connections() 'kind' parameter mapping # =================================================================== 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]), } if AF_INET6 is not None: conn_tmap.update({ "tcp6": ([AF_INET6], [SOCK_STREAM]), "udp6": ([AF_INET6], [SOCK_DGRAM]), }) if AF_UNIX is not None: conn_tmap.update({ "unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]), }) # ===================================================================== # --- Exceptions # ===================================================================== class Error(Exception): """Base exception class. All other psutil exceptions inherit from this one. """ __module__ = 'psutil' def _infodict(self, attrs): info = collections.OrderedDict() for name in attrs: value = getattr(self, name, None) if value: info[name] = value elif name == "pid" and value == 0: info[name] = value return info def __str__(self): # invoked on `raise Error` info = self._infodict(("pid", "ppid", "name")) if info: details = "(%s)" % ", ".join( ["%s=%r" % (k, v) for k, v in info.items()]) else: details = None return " ".join([x for x in (getattr(self, "msg", ""), details) if x]) def __repr__(self): # invoked on `repr(Error)` info = self._infodict(("pid", "ppid", "name", "seconds", "msg")) details = ", ".join(["%s=%r" % (k, v) for k, v in info.items()]) return "psutil.%s(%s)" % (self.__class__.__name__, details) 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 "" class TimeoutExpired(Error): """Raised on Process.wait(timeout) if timeout expires and process is still alive. """ __module__ = 'psutil' def __init__(self, seconds, pid=None, name=None): Error.__init__(self) self.seconds = seconds self.pid = pid self.name = name self.msg = "timeout after %s seconds" % seconds # =================================================================== # --- utils # =================================================================== # This should be in _compat.py rather than here, but does not work well # with setup.py importing this module via a sys.path trick. if PY3: if isinstance(__builtins__, dict): # cpython exec_ = __builtins__["exec"] else: # pypy exec_ = getattr(__builtins__, "exec") # noqa exec_("""def raise_from(value, from_value): try: raise value from from_value finally: value = None """) else: def raise_from(value, from_value): raise value 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 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() >>> It supports: - functions - classes (acts as a @singleton) - staticmethods - classmethods It does NOT support: - methods """ @functools.wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items()))) try: return cache[key] except KeyError: try: ret = cache[key] = fun(*args, **kwargs) except Exception as err: raise raise_from(err, None) return ret def cache_clear(): """Clear cache.""" cache.clear() cache = {} wrapper.cache_clear = cache_clear return wrapper 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 try: return fun(self) except Exception as err: raise raise_from(err, None) except KeyError: # case 3: we entered oneshot() ctx but there's no cache # for this entry yet try: ret = fun(self) except Exception as err: raise raise_from(err, None) 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 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) 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 @memoize 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 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 def sockfam_to_enum(num): """Convert a numeric socket family value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.AddressFamily(num) except ValueError: return num def socktype_to_enum(num): """Convert a numeric socket type value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.SocketKind(num) except ValueError: return num 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) 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 class _WrapNumbers: """Watches numbers so that they don't overflow and wrap (reset to zero). """ def __init__(self): self.lock = threading.Lock() self.cache = {} self.reminders = {} self.reminder_keys = {} def _add_dict(self, input_dict, name): assert name not in self.cache assert name not in self.reminders assert name not in self.reminder_keys self.cache[name] = input_dict self.reminders[name] = collections.defaultdict(int) self.reminder_keys[name] = collections.defaultdict(set) def _remove_dead_reminders(self, input_dict, name): """In case the number of keys changed between calls (e.g. a disk disappears) this removes the entry from self.reminders. """ old_dict = self.cache[name] gone_keys = set(old_dict.keys()) - set(input_dict.keys()) for gone_key in gone_keys: for remkey in self.reminder_keys[name][gone_key]: del self.reminders[name][remkey] del self.reminder_keys[name][gone_key] def run(self, input_dict, name): """Cache dict and sum numbers which overflow and wrap. Return an updated copy of `input_dict` """ if name not in self.cache: # This was the first call. self._add_dict(input_dict, name) return input_dict self._remove_dead_reminders(input_dict, name) old_dict = self.cache[name] new_dict = {} for key in input_dict.keys(): input_tuple = input_dict[key] try: old_tuple = old_dict[key] except KeyError: # The input dict has a new key (e.g. a new disk or NIC) # which didn't exist in the previous call. new_dict[key] = input_tuple continue bits = [] for i in range(len(input_tuple)): input_value = input_tuple[i] old_value = old_tuple[i] remkey = (key, i) if input_value < old_value: # it wrapped! self.reminders[name][remkey] += old_value self.reminder_keys[name][key].add(remkey) bits.append(input_value + self.reminders[name][remkey]) new_dict[key] = tuple(bits) self.cache[name] = input_dict return new_dict def cache_clear(self, name=None): """Clear the internal cache, optionally only for function 'name'.""" with self.lock: if name is None: self.cache.clear() self.reminders.clear() self.reminder_keys.clear() else: self.cache.pop(name, None) self.reminders.pop(name, None) self.reminder_keys.pop(name, None) def cache_info(self): """Return internal cache dicts as a tuple of 3 elements.""" with self.lock: return (self.cache, self.reminders, self.reminder_keys) 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) _wn = _WrapNumbers() wrap_numbers.cache_clear = _wn.cache_clear wrap_numbers.cache_info = _wn.cache_info # The read buffer size for open() builtin. This (also) dictates how # much data we read(2) when iterating over file lines as in: # >>> with open(file) as f: # ... for line in f: # ... ... # Default per-line buffer size for binary files is 1K. For text files # is 8K. We use a bigger buffer (32K) in order to have more consistent # results when reading /proc pseudo files on Linux, see: # https://github.com/giampaolo/psutil/issues/2050 # On Python 2 this also speeds up the reading of big files: # (namely /proc/{pid}/smaps and /proc/net/*): # https://github.com/giampaolo/psutil/issues/708 FILE_READ_BUFFER_SIZE = 32 * 1024 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 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 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 abs(n) >= prefix[symbol]: value = float(n) / prefix[symbol] return format % locals() return format % dict(symbol=symbols[0], value=n) def get_procfs_path(): """Return updated psutil.PROCFS_PATH constant.""" return sys.modules['psutil'].PROCFS_PATH if PY3: def decode(s): return s.decode(encoding=ENCODING, errors=ENCODING_ERRS) else: def decode(s): return s # ===================================================================== # --- shell utils # ===================================================================== @memoize 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) 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) def debug(msg): """If PSUTIL_DEBUG env var is set, print a debug message to stderr.""" if PSUTIL_DEBUG: import inspect fname, lineno, _, 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)
29,186
30.149413
81
py

Dataset Card for "AlgorithmicResearchGroup/arxiv_research_code"

Dataset Description

https://huggingface.co./datasets/AlgorithmicResearchGroup/arxiv_research_code

Dataset Summary

ArtifactAI/arxiv_research_code contains over 21.8GB of source code files referenced strictly in ArXiv papers. The dataset serves as a curated dataset for Code LLMs.

How to use it

from datasets import load_dataset

# full dataset (21.8GB of data)
ds = load_dataset("AlgorithmicResearchGroup/arxiv_research_code", split="train")

# dataset streaming (will only download the data as needed)
ds = load_dataset("AlgorithmicResearchGroup/arxiv_research_code", streaming=True, split="train")
for sample in iter(ds): print(sample["code"])

Dataset Structure

Data Instances

Each data instance corresponds to one file. The content of the file is in the code feature, and other features (repo, file, etc.) provide some metadata.

Data Fields

  • repo (string): code repository name.
  • file (string): file path in the repository.
  • code (string): code within the file.
  • file_length: (integer): number of characters in the file.
  • avg_line_length: (float): the average line-length of the file.
  • max_line_length: (integer): the maximum line-length of the file.
  • extension_type: (string): file extension.

Data Splits

The dataset has no splits and all data is loaded as train split by default.

Dataset Creation

Source Data

Initial Data Collection and Normalization

34,099 active GitHub repository names were extracted from ArXiv papers from its inception through July 21st, 2023 totaling 773G of compressed github repositories.

These repositories were then filtered, and the code from each file was extracted into 4.7 million files.

Who are the source language producers?

The source (code) language producers are users of GitHub that created unique repository

Personal and Sensitive Information

The released dataset may contain sensitive information such as emails, IP addresses, and API/ssh keys that have previously been published to public repositories on GitHub.

Additional Information

Dataset Curators

Matthew Kenney, AlgorithmicResearchGroup, [email protected]

Citation Information

@misc{arxiv_research_code,
    title={arxiv_research_code},
    author={Matthew Kenney},
    year={2023}
}
Downloads last month
84