summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGiampaolo Rodola <g.rodola@gmail.com>2019-03-13 16:27:07 +0100
committerGiampaolo Rodola <g.rodola@gmail.com>2019-03-14 19:27:33 +0100
commit3325a8ecd486100659f4017f2544202e7f6d3c29 (patch)
treed0b2e30cc7efebd6ab6cca568a4615a5947197d2
parent3762d0f8d6206bd70b16647d0f2c11172ef958db (diff)
downloadpsutil-3325a8ecd486100659f4017f2544202e7f6d3c29.tar.gz
Big docfix (#1464)
* use https wherever possible * always point to python 3 doc * point to new MSDN urls * use RST references and avoid repetitions of URLs
-rw-r--r--.github/ISSUE_TEMPLATE/bug.md10
-rw-r--r--.github/ISSUE_TEMPLATE/enhancement.md3
-rw-r--r--CREDITS5
-rw-r--r--HISTORY.rst6
-rw-r--r--docs/DEVGUIDE.rst80
-rw-r--r--docs/index.rst331
-rw-r--r--psutil/__init__.py2
-rw-r--r--psutil/tests/__init__.py14
-rwxr-xr-xpsutil/tests/runner.py14
-rwxr-xr-xpsutil/tests/test_bsd.py32
-rwxr-xr-xpsutil/tests/test_linux.py177
-rwxr-xr-xpsutil/tests/test_osx.py14
-rwxr-xr-xpsutil/tests/test_posix.py10
-rwxr-xr-xpsutil/tests/test_process.py4
-rwxr-xr-xpsutil/tests/test_system.py6
-rwxr-xr-xpsutil/tests/test_windows.py6
16 files changed, 369 insertions, 345 deletions
diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md
index 9f377b2f..f72fe779 100644
--- a/.github/ISSUE_TEMPLATE/bug.md
+++ b/.github/ISSUE_TEMPLATE/bug.md
@@ -9,10 +9,18 @@ assignees: 'giampaolo'
**Platform**
* { OS version }
-* { psutil version (pip show psutil) }
+* { psutil version (use `pip show psutil`) }
**Bug description**
{ a clear and concise description of what the bug is }
```
traceback message (if any)
```
+
+**Test results**
+{ This is an extra: you may want to run `python -c psutil.tests`. }
+{ If you have failures paste those only (not the full test output). }
+{ If the failures look unrelated with the issue at hand open another ticket }
+```
+test failure output
+```
diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md
index 408728ee..acf323a6 100644
--- a/.github/ISSUE_TEMPLATE/enhancement.md
+++ b/.github/ISSUE_TEMPLATE/enhancement.md
@@ -1,11 +1,8 @@
---
name: Enhancement
about: Propose an enhancement
-title: "title"
labels: 'enhancement'
assignees: 'giampaolo'
---
-{ describe the proposal }
-
diff --git a/CREDITS b/CREDITS
index d9424725..38cd6939 100644
--- a/CREDITS
+++ b/CREDITS
@@ -587,3 +587,8 @@ N: Ghislain Le Meur
W: https://github.com/gigi206
D: idea for Process.parents()
I: 1379
+
+N: Benjamin Drung
+D: make tests invariant to LANG setting
+W: https://github.com/bdrung
+I: 1462
diff --git a/HISTORY.rst b/HISTORY.rst
index cd71108d..9e2b5477 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -6,6 +6,12 @@
**Enhancements**
- 1458_: provide coloured test output. Also show failures on KeyboardInterrupt.
+- 1464_: various docfixes (always point to python3 doc, fix links, etc.).
+
+**Bug fixes**
+
+- 1462_: [Linux] (tests) make tests invariant to LANG setting (patch by
+ Benjamin Drung)
5.6.1
=====
diff --git a/docs/DEVGUIDE.rst b/docs/DEVGUIDE.rst
index f587ebcc..d9eb6d7a 100644
--- a/docs/DEVGUIDE.rst
+++ b/docs/DEVGUIDE.rst
@@ -21,11 +21,9 @@ If you plan on hacking on psutil this is what you're supposed to do first:
make test
-- bear in mind that ``make``
- (see `Makefile <https://github.com/giampaolo/psutil/blob/master/Makefile>`_)
- is the designated tool to run tests, build, install etc. and that it is also
- available on Windows
- (see `make.bat <https://github.com/giampaolo/psutil/blob/master/make.bat>`_).
+- bear in mind that ``make``(see `Makefile`_) is the designated tool to run
+ tests, build, install etc. and that it is also available on Windows (see
+ `make.bat`_ ).
- do not use ``sudo``; ``make install`` installs psutil as a limited user in
"edit" mode; also ``make setup-dev-env`` installs deps as a limited user.
- use `make help` to see the list of available commands.
@@ -33,10 +31,9 @@ If you plan on hacking on psutil this is what you're supposed to do first:
Coding style
============
-- python code strictly follows `PEP 8 <https://www.python.org/dev/peps/pep-0008/>`_
- styling guides and this is enforced by ``make install-git-hooks``.
-- C code strictly follows `PEP 7 <https://www.python.org/dev/peps/pep-0007/>`_
- styling guides.
+- python code strictly follows `PEP-8`_ styling guides and this is enforced by
+ a commit GIT hook installed via ``make install-git-hooks``.
+- C code follows `PEP-7`_ styling guides.
Makefile
========
@@ -100,30 +97,30 @@ Usually the files involved when adding a new functionality are:
Typical process occurring when adding a new functionality (API):
-- define the new function in ``psutil/__init__.py``.
+- define the new function in `psutil/__init__.py`_.
- write the platform specific implementation in ``psutil/_ps{platform}.py``
- (e.g. ``psutil/_pslinux.py``).
+ (e.g. `psutil/_pslinux.py`_).
- if the change requires C, write the C implementation in
- ``psutil/_psutil_{platform}.c`` (e.g. ``psutil/_psutil_linux.c``).
-- write a generic test in ``psutil/tests/test_system.py`` or
- ``psutil/tests/test_process.py``.
+ ``psutil/_psutil_{platform}.c`` (e.g. `psutil/_psutil_linux.c`_).
+- write a generic test in `psutil/tests/test_system.py`_ or
+ `psutil/tests/test_process.py`_.
- if possible, write a platform specific test in
- ``psutil/tests/test_{platform}.py`` (e.g. ``test_linux.py``).
+ ``psutil/tests/test_{platform}.py`` (e.g. `psutil/tests/test_linux.py`_).
This usually means testing the return value of the new feature against
a system CLI tool.
- update doc in ``doc/index.py``.
- update ``HISTORY.rst``.
-- update ``README.rst`` (if necessary).
- make a pull request.
Make a pull request
===================
-- fork psutil
-- create your feature branch (``git checkout -b my-new-feature``)
-- commit your changes (``git commit -am 'add some feature'``)
-- push to the branch (``git push origin my-new-feature``)
-- create a new pull request
+- fork psutil (go to https://github.com/giampaolo/psutil and click on "fork")
+- git clone your fork locally: ``git clone git@github.com:YOUR-USERNAME/psutil.git``)
+- create your feature branch:``git checkout -b new-feature``
+- commit your changes: ``git commit -am 'add some feature'``
+- push to the branch: ``git push origin new-feature``
+- create a new pull request by via github web interface
Continuous integration
======================
@@ -136,13 +133,10 @@ Unit tests
Tests are automatically run for every GIT push on **Linux**, **macOS** and
**Windows** by using:
-- `Travis <https://travis-ci.org/giampaolo/psutil>`_ (Linux, macOS)
-- `Appveyor <https://ci.appveyor.com/project/giampaolo/psutil>`_ (Windows)
+- `Travis`_ (Linux, macOS)
+- `Appveyor`_ (Windows)
-Test files controlling these are
-`.travis.yml <https://github.com/giampaolo/psutil/blob/master/.travis.yml>`_
-and
-`appveyor.yml <https://github.com/giampaolo/psutil/blob/master/appveyor.yml>`_.
+Test files controlling these are `.travis.yml`_ and `appveyor.yml`_.
Both services run psutil test suite against all supported python version
(2.6 - 3.6).
Two icons in the home page (README) always show the build status:
@@ -160,9 +154,8 @@ BSD, AIX and Solaris are currently tested manually.
Test coverage
-------------
-Test coverage is provided by `coveralls.io <https://coveralls.io/github/giampaolo/psutil>`_,
-it is controlled via `.travis.yml <https://github.com/giampaolo/psutil/blob/master/.travis.yml>`_
-and it is updated on every git push.
+Test coverage is provided by `coveralls.io`_ and it is controlled via
+`.travis.yml`_.
An icon in the home page (README) always shows the last coverage percentage:
.. image:: https://coveralls.io/repos/giampaolo/psutil/badge.svg?branch=master&service=github
@@ -172,9 +165,9 @@ An icon in the home page (README) always shows the last coverage percentage:
Documentation
=============
-- doc source code is written in a single file: `/docs/index.rst <https://raw.githubusercontent.com/giampaolo/psutil/master/docs/index.rst>`_.
-- it uses `RsT syntax <http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_
- and it's built with `sphinx <http://sphinx-doc.org/>`_.
+- doc source code is written in a single file: `/docs/index.rst`_.
+- it uses `RsT syntax`_
+ and it's built with `sphinx`_.
- doc can be built with ``make setup-dev-env; cd docs; make html``.
- public doc is hosted on http://psutil.readthedocs.io/
@@ -186,3 +179,24 @@ These are notes for myself (Giampaolo):
- ``make release``
- post announce (``make print-announce``) on psutil and python-announce mailing
lists, twitter, g+, blog.
+
+
+.. _`.travis.yml`: https://github.com/giampaolo/psutil/blob/master/.travis.ym
+.. _`appveyor.yml`: https://github.com/giampaolo/psutil/blob/master/appveyor.ym
+.. _`Appveyor`: https://ci.appveyor.com/project/giampaolo/psuti
+.. _`coveralls.io`: https://coveralls.io/github/giampaolo/psuti
+.. _`doc/index.rst`: https://github.com/giampaolo/psutil/blob/master/doc/index.rst
+.. _`HISTORY.rst`: https://github.com/giampaolo/psutil/blob/master/HISTORY.rst
+.. _`make.bat`: https://github.com/giampaolo/psutil/blob/master/make.bat
+.. _`Makefile`: https://github.com/giampaolo/psutil/blob/master/Makefile
+.. _`PEP-7`: https://www.python.org/dev/peps/pep-0007/
+.. _`PEP-8`: https://www.python.org/dev/peps/pep-0008/
+.. _`psutil/__init__.py`: https://github.com/giampaolo/psutil/blob/master/psutil/__init__.py
+.. _`psutil/_pslinux.py`: https://github.com/giampaolo/psutil/blob/master/psutil/_pslinux.py
+.. _`psutil/_psutil_linux.c`: https://github.com/giampaolo/psutil/blob/master/psutil/_psutil_linux.c
+.. _`psutil/tests/test_linux.py`: https://github.com/giampaolo/psutil/blob/master/psutil/tests/test_linux.py
+.. _`psutil/tests/test_process.py`: https://github.com/giampaolo/psutil/blob/master/psutil/tests/test_process.py
+.. _`psutil/tests/test_system.py`: https://github.com/giampaolo/psutil/blob/master/psutil/tests/test_system.py
+.. _`RsT syntax`: http://docutils.sourceforge.net/docs/user/rst/quickref.htm
+.. _`sphinx`: http://sphinx-doc.org
+.. _`Travis`: https://travis-ci.org/giampaolo/psuti
diff --git a/docs/index.rst b/docs/index.rst
index f35b23c3..6ff1e22c 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -37,7 +37,8 @@ psutil currently supports the following platforms:
- **Sun Solaris**
- **AIX**
-...both **32-bit** and **64-bit** architectures. Supported Python versions are **2.6**, **2.7** and **3.4+**. `PyPy <http://pypy.org/>`__ is also known to work.
+Supported Python versions are **2.6**, **2.7** and **3.4+**.
+`PyPy <http://pypy.org/>`__ is also known to work.
The psutil documentation you're reading is distributed as a single HTML page.
@@ -158,8 +159,7 @@ CPU
.. function:: cpu_count(logical=True)
- Return the number of logical CPUs in the system (same as
- `os.cpu_count() <http://docs.python.org/3/library/os.html#os.cpu_count>`__
+ Return the number of logical CPUs in the system (same as `os.cpu_count`_
in Python 3.4) or ``None`` if undetermined.
If *logical* is ``False`` return the number of physical cores only (hyper
thread CPUs are excluded) or ``None`` if undetermined.
@@ -275,8 +275,8 @@ Memory
The sum of **used** and **available** does not necessarily equal **total**.
On Windows **available** and **free** are the same.
- See `meminfo.py <https://github.com/giampaolo/psutil/blob/master/scripts/meminfo.py>`__
- script providing an example on how to convert bytes in a human readable form.
+ See `meminfo.py`_ script providing an example on how to convert bytes in a
+ human readable form.
.. note:: if you just want to know how much physical memory is left in a
cross platform fashion simply rely on the **available** field.
@@ -311,8 +311,8 @@ Memory
(cumulative)
**sin** and **sout** on Windows are always set to ``0``.
- See `meminfo.py <https://github.com/giampaolo/psutil/blob/master/scripts/meminfo.py>`__
- script providing an example on how to convert bytes in a human readable form.
+ See `meminfo.py`_ script providing an example on how to convert bytes in a
+ human readable form.
>>> import psutil
>>> psutil.swap_memory()
@@ -332,21 +332,17 @@ Disks
mount point and filesystem type, similarly to "df" command on UNIX. If *all*
parameter is ``False`` it tries to distinguish and return physical devices
only (e.g. hard disks, cd-rom drives, USB keys) and ignore all others
- (e.g. memory partitions such as
- `/dev/shm <http://www.cyberciti.biz/tips/what-is-devshm-and-its-practical-usage.html>`__).
+ (e.g. memory partitions such as /dev/shm).
Note that this may not be fully reliable on all systems (e.g. on BSD this
parameter is ignored).
Named tuple's **fstype** field is a string which varies depending on the
platform.
On Linux it can be one of the values found in /proc/filesystems (e.g.
``'ext3'`` for an ext3 hard drive o ``'iso9660'`` for the CD-ROM drive).
- On Windows it is determined via
- `GetDriveType <http://msdn.microsoft.com/en-us/library/aa364939(v=vs.85).aspx>`__
- and can be either ``"removable"``, ``"fixed"``, ``"remote"``, ``"cdrom"``,
- ``"unmounted"`` or ``"ramdisk"``. On macOS and BSD it is retrieved via
- `getfsstat(2) <http://www.manpagez.com/man/2/getfsstat/>`__. See
- `disk_usage.py <https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py>`__
- script providing an example usage.
+ On Windows it is determined via `GetDriveType`_ and can be either
+ ``"removable"``, ``"fixed"``, ``"remote"``, ``"cdrom"``, ``"unmounted"`` or
+ ``"ramdisk"``. On macOS and BSD it is retrieved via `getfsstat`_ syscall.
+ See `disk_usage.py`_ script providing an example usage.
>>> import psutil
>>> psutil.disk_partitions()
@@ -358,12 +354,10 @@ Disks
Return disk usage statistics about the partition which contains the given
*path* as a named tuple including **total**, **used** and **free** space
expressed in bytes, plus the **percentage** usage.
- `OSError <http://docs.python.org/3/library/exceptions.html#OSError>`__ is
- raised if *path* does not exist.
- Starting from `Python 3.3 <http://bugs.python.org/issue12442>`__ this is
- also available as
- `shutil.disk_usage() <http://docs.python.org/3/library/shutil.html#shutil.disk_usage>`__.
- See `disk_usage.py <https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py>`__ script providing an example usage.
+ ``OSError`` is raised if *path* does not exist.
+ Starting from Python 3.3 this is also available as `shutil.disk_usage`_
+ (see `BPO-12442`_).
+ See `disk_usage.py`_ script providing an example usage.
>>> import psutil
>>> psutil.disk_usage('/')
@@ -400,16 +394,13 @@ Disks
(in milliseconds)
- **busy_time**: (*Linux*, *FreeBSD*) time spent doing actual I/Os (in
milliseconds)
- - **read_merged_count** (*Linux*): number of merged reads
- (see `iostat doc <https://www.kernel.org/doc/Documentation/iostats.txt>`__)
- - **write_merged_count** (*Linux*): number of merged writes
- (see `iostats doc <https://www.kernel.org/doc/Documentation/iostats.txt>`__)
+ - **read_merged_count** (*Linux*): number of merged reads (see `iostats doc`_)
+ - **write_merged_count** (*Linux*): number of merged writes (see `iostats doc`_)
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 named tuple described above as the values.
- See `iotop.py <https://github.com/giampaolo/psutil/blob/master/scripts/iotop.py>`__
- for an example application.
+ See `iotop.py`_ for an example application.
On some systems such as Linux, on a very busy or long-lived system, the
numbers returned by the kernel may overflow and wrap (restart from zero).
If *nowrap* is ``True`` psutil will detect and adjust those numbers across
@@ -485,9 +476,7 @@ Network
{'lo': snetio(bytes_sent=547971, bytes_recv=547971, packets_sent=5075, packets_recv=5075, errin=0, errout=0, dropin=0, dropout=0),
'wlan0': snetio(bytes_sent=13921765, bytes_recv=62162574, packets_sent=79097, packets_recv=89648, errin=0, errout=0, dropin=0, dropout=0)}
- Also see `nettop.py <https://github.com/giampaolo/psutil/blob/master/scripts/nettop.py>`__
- and `ifconfig.py <https://github.com/giampaolo/psutil/blob/master/scripts/ifconfig.py>`__
- for an example application.
+ Also see `nettop.py`_ and `ifconfig.py`_ for an example application.
.. versionchanged::
5.3.0 numbers no longer wrap (restart from zero) across calls thanks to new
@@ -499,18 +488,11 @@ Network
Every named tuple provides 7 attributes:
- **fd**: the socket file descriptor. If the connection refers to the current
- process this may be passed to
- `socket.fromfd() <http://docs.python.org/library/socket.html#socket.fromfd>`__
+ process this may be passed to `socket.fromfd`_
to obtain a usable socket object.
On Windows and SunOS this is always set to ``-1``.
- - **family**: the address family, either `AF_INET
- <http://docs.python.org//library/socket.html#socket.AF_INET>`__,
- `AF_INET6 <http://docs.python.org//library/socket.html#socket.AF_INET6>`__
- or `AF_UNIX <http://docs.python.org//library/socket.html#socket.AF_UNIX>`__.
- - **type**: the address type, either `SOCK_STREAM
- <http://docs.python.org//library/socket.html#socket.SOCK_STREAM>`__ or
- `SOCK_DGRAM
- <http://docs.python.org//library/socket.html#socket.SOCK_DGRAM>`__.
+ - **family**: the address family, either `AF_INET`_, `AF_INET6`_ or `AF_UNIX`_.
+ - **type**: the address type, either `SOCK_STREAM`_ or `SOCK_DGRAM`_.
- **laddr**: the local address as a ``(ip, port)`` named tuple or a ``path``
in case of AF_UNIX sockets. For UNIX sockets see notes below.
- **raddr**: the remote address as a ``(ip, port)`` named tuple or an
@@ -559,8 +541,7 @@ Network
On macOS and AIX this function requires root privileges.
To get per-process connections use :meth:`Process.connections`.
- Also, see
- `netstat.py sample script <https://github.com/giampaolo/psutil/blob/master/scripts/netstat.py>`__.
+ Also, see `netstat.py`_ example script.
Example:
>>> import psutil
@@ -600,9 +581,7 @@ Network
value is a list of named tuples for each address assigned to the NIC.
Each named tuple includes 5 fields:
- - **family**: the address family, either
- `AF_INET <http://docs.python.org//library/socket.html#socket.AF_INET>`__,
- `AF_INET6 <http://docs.python.org//library/socket.html#socket.AF_INET6>`__
+ - **family**: the address family, either `AF_INET`_ or `AF_INET6`_
or :const:`psutil.AF_LINK`, which refers to a MAC address.
- **address**: the primary NIC address (always set).
- **netmask**: the netmask address (may be ``None``).
@@ -623,9 +602,7 @@ Network
snicaddr(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
>>>
- See also `nettop.py <https://github.com/giampaolo/psutil/blob/master/scripts/nettop.py>`__
- and `ifconfig.py <https://github.com/giampaolo/psutil/blob/master/scripts/ifconfig.py>`__
- for an example application.
+ See also `nettop.py`_ and `ifconfig.py`_ for an example application.
.. note::
if you're interested in others families (e.g. AF_BLUETOOTH) you can use
@@ -667,9 +644,7 @@ Network
{'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536)}
- Also see `nettop.py <https://github.com/giampaolo/psutil/blob/master/scripts/nettop.py>`__
- and `ifconfig.py <https://github.com/giampaolo/psutil/blob/master/scripts/ifconfig.py>`__
- for an example application.
+ Also see `nettop.py`_ and `ifconfig.py`_ for an example application.
.. versionadded:: 3.0.0
@@ -697,8 +672,7 @@ Sensors
shwtemp(label='Core 2', current=45.0, high=100.0, critical=100.0),
shwtemp(label='Core 3', current=47.0, high=100.0, critical=100.0)]}
- See also `temperatures.py <https://github.com/giampaolo/psutil/blob/master/scripts/temperatures.py>`__ and `sensors.py <https://github.com/giampaolo/psutil/blob/master/scripts/sensors.py>`__
- for an example application.
+ See also `temperatures.py`_ and `sensors.py`_ for an example application.
Availability: Linux, FreeBSD
@@ -718,8 +692,7 @@ Sensors
>>> psutil.sensors_fans()
{'asus': [sfan(label='cpu_fan', current=3200)]}
- See also `fans.py <https://github.com/giampaolo/psutil/blob/master/scripts/fans.py>`__ and `sensors.py <https://github.com/giampaolo/psutil/blob/master/scripts/sensors.py>`__
- for an example application.
+ See also `fans.py`_ and `sensors.py`_ for an example application.
Availability: Linux, macOS
@@ -756,7 +729,7 @@ Sensors
>>> print("charge = %s%%, time left = %s" % (battery.percent, secs2hours(battery.secsleft)))
charge = 93%, time left = 4:37:08
- See also `battery.py <https://github.com/giampaolo/psutil/blob/master/scripts/battery.py>`__ and `sensors.py <https://github.com/giampaolo/psutil/blob/master/scripts/sensors.py>`__ for an example application.
+ See also `battery.py`_ and `sensors.py`_ for an example application.
Availability: Linux, Windows, FreeBSD
@@ -782,8 +755,7 @@ Other system info
.. note::
on Windows this function may return a time which is off by 1 second if it's
- used across different processes (see
- `issue #1007 <https://github.com/giampaolo/psutil/issues/1007>`__).
+ used across different processes (see `issue #1007`_).
.. function:: users()
@@ -976,18 +948,15 @@ Process class
.. class:: Process(pid=None)
Represents an OS process with the given *pid*.
- If *pid* is omitted current process *pid*
- (`os.getpid() <http://docs.python.org/library/os.html#os.getpid>`__) is used.
+ If *pid* is omitted current process *pid* (`os.getpid`_) is used.
Raise :class:`NoSuchProcess` if *pid* does not exist.
On Linux *pid* can also refer to a thread ID (the *id* field returned by
:meth:`threads` method).
When accessing methods of this class always be prepared to catch
:class:`NoSuchProcess` and :class:`AccessDenied` exceptions.
- `hash() <https://docs.python.org/3/library/functions.html#hash>`__ builtin can
- be used against instances of this class in order to identify a process
- univocally over time (the hash is determined by mixing process PID
- + creation time). As such it can also be used with
- `set()s <https://docs.python.org/3/library/stdtypes.html#types-set>`__.
+ `hash`_ builtin can be used against instances of this class in order to
+ identify a process univocally over time (the hash is determined by mixing
+ process PID + creation time). As such it can also be used with `set`_.
.. note::
@@ -1105,16 +1074,13 @@ Process class
.. method:: ppid()
The process parent PID. On Windows the return value is cached after first
- call. Not on POSIX because
- `ppid may change <https://github.com/giampaolo/psutil/issues/321>`__
- if process becomes a zombie.
+ call. Not on POSIX because ppid may change if process becomes a zombie
See also :meth:`parent` and :meth:`parents` methods.
.. method:: name()
The process name. On Windows the return value is cached after first
- call. Not on POSIX because the process name
- `may change <https://github.com/giampaolo/psutil/issues/692>`__.
+ call. Not on POSIX because the process name may change.
See also how to `find a process by name <#find-process-by-name>`__.
.. method:: exe()
@@ -1153,9 +1119,7 @@ Process class
.. method:: create_time()
The process creation time as a floating point number expressed in seconds
- since the epoch, in
- `UTC <http://en.wikipedia.org/wiki/Coordinated_universal_time>`__.
- The return value is cached after first call.
+ since the epoch, in UTC. The return value is cached after first call.
>>> import psutil, datetime
>>> p = psutil.Process()
@@ -1222,19 +1186,15 @@ Process class
.. method:: uids()
- The real, effective and saved user ids of this process as a
- named tuple. This is the same as
- `os.getresuid() <http://docs.python.org//library/os.html#os.getresuid>`__
- but can be used for any process PID.
+ The real, effective and saved user ids of this process as a named tuple.
+ This is the same as `os.getresuid`_ but can be used for any process PID.
Availability: UNIX
.. method:: gids()
- The real, effective and saved group ids of this process as a
- named tuple. This is the same as
- `os.getresgid() <http://docs.python.org//library/os.html#os.getresgid>`__
- but can be used for any process PID.
+ The real, effective and saved group ids of this process as a named tuple.
+ This is the same as `os.getresgid`_ but can be used for any process PID.
Availability: UNIX
@@ -1247,8 +1207,7 @@ Process class
.. method:: nice(value=None)
- Get or set process
- `niceness <blogs.techrepublic.com.com/opensource/?p=140>`__ (priority).
+ Get or set process niceness (priority).
On UNIX this is a number which usually goes from ``-20`` to ``20``.
The higher the nice value, the lower the priority of the process.
@@ -1259,16 +1218,10 @@ Process class
10
>>>
- Starting from `Python 3.3 <http://bugs.python.org/issue10784>`__ this
- functionality is also available as
- `os.getpriority() <http://docs.python.org/3/library/os.html#os.getpriority>`__
- and
- `os.setpriority() <http://docs.python.org/3/library/os.html#os.setpriority>`__
- (UNIX only).
- On Windows this is implemented via
- `GetPriorityClass <http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx>`__
- and `SetPriorityClass <http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx>`__
- Windows APIs and *value* is one of the
+ Starting from Python 3.3 this functionality is also available as
+ `os.getpriority`_ and `os.setpriority`_ (see `BPO-10784`_).
+ On Windows this is implemented via `GetPriorityClass`_ and
+ `SetPriorityClass`_ Windows APIs and *value* is one of the
:data:`psutil.*_PRIORITY_CLASS <psutil.ABOVE_NORMAL_PRIORITY_CLASS>`
constants reflecting the MSDN documentation.
Example which increases process priority on Windows:
@@ -1277,9 +1230,7 @@ Process class
.. method:: ionice(ioclass=None, value=None)
- Get or set
- `process I/O niceness <http://friedcpu.wordpress.com/2007/07/17/why-arent-you-using-ionice-yet/>`__ (priority).
- On Linux *ioclass* is one of the
+ Get or set process I/O niceness (priority). On Linux *ioclass* is one of the
:data:`psutil.IOPRIO_CLASS_*<psutil.IOPRIO_CLASS_NONE>` 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
@@ -1307,14 +1258,11 @@ Process class
.. method:: rlimit(resource, limits=None)
- Get or set process resource limits (see
- `man prlimit <http://linux.die.net/man/2/prlimit>`__). *resource* is one
+ Get or set process resource limits (see `man prlimit`_). *resource* is one
of the :data:`psutil.RLIMIT_* <psutil.RLIM_INFINITY>` constants.
*limits* is a ``(soft, hard)`` tuple.
- This is the same as `resource.getrlimit() <http://docs.python.org/library/resource.html#resource.getrlimit>`__
- and `resource.setrlimit() <http://docs.python.org/library/resource.html#resource.setrlimit>`__
- but can be used for any process PID, not only
- `os.getpid() <http://docs.python.org/library/os.html#os.getpid>`__.
+ This is the same as `resource.getrlimit`_ and `resource.setrlimit`_
+ but can be used for any process PID, not only `os.getpid`_.
For get, return value is a ``(soft, hard)`` tuple. Each value may be either
and integer or :data:`psutil.RLIMIT_* <psutil.RLIM_INFINITY>`.
Example:
@@ -1336,7 +1284,7 @@ Process class
Return process I/O statistics as a named tuple.
For Linux you can refer to
- `/proc filesysem documentation <http://stackoverflow.com/a/3634088>`__.
+ `/proc filesysem documentation <https://stackoverflow.com/questions/3633286/>`__.
- **read_count**: the number of read operations performed (cumulative).
This is supposed to count the number of read-related syscalls such as
@@ -1414,9 +1362,7 @@ Process class
`explanation <http://stackoverflow.com/questions/556405/>`__).
On Windows and macOS only *user* and *system* are filled, the others are
set to ``0``.
- This is similar to
- `os.times() <http://docs.python.org//library/os.html#os.times>`__
- but can be used for any process PID.
+ This is similar to `os.times`_ but can be used for any process PID.
.. versionchanged::
4.1.0 return two extra fields: *children_user* and *children_system*.
@@ -1506,7 +1452,7 @@ Process class
On FreeBSD certain kernel process may return ``-1``.
It may be used in conjunction with ``psutil.cpu_percent(percpu=True)`` to
observe the system workload distributed across multiple CPUs as shown by
- `cpu_distribution.py <https://github.com/giampaolo/psutil/blob/master/scripts/cpu_distribution.py>`__ example script.
+ `cpu_distribution.py`_ example script.
Availability: Linux, FreeBSD, SunOS
@@ -1549,32 +1495,27 @@ Process class
- **rss**: aka "Resident Set Size", this is the non-swapped physical
memory a process has used.
- On UNIX it matches "top"'s RES column
- (see `doc <http://linux.die.net/man/1/top>`__).
+ On UNIX it matches "top"'s RES column).
On Windows this is an alias for `wset` field and it matches "Mem Usage"
column of taskmgr.exe.
- **vms**: aka "Virtual Memory Size", this is the total amount of virtual
memory used by the process.
- On UNIX it matches "top"'s VIRT column
- (see `doc <http://linux.die.net/man/1/top>`__).
+ On UNIX it matches "top"'s VIRT column.
On Windows this is an alias for `pagefile` field and it matches
"Mem Usage" "VM Size" column of taskmgr.exe.
- **shared**: *(Linux)*
memory that could be potentially shared with other processes.
- This matches "top"'s SHR column
- (see `doc <http://linux.die.net/man/1/top>`__).
+ This matches "top"'s SHR column).
- **text** *(Linux, BSD)*:
aka TRS (text resident set) the amount of memory devoted to
- executable code. This matches "top"'s CODE column
- (see `doc <http://linux.die.net/man/1/top>`__).
+ executable code. This matches "top"'s CODE column).
- **data** *(Linux, BSD)*:
aka DRS (data resident set) the amount of physical memory devoted to
- other than executable code. It matches "top"'s DATA column
- (see `doc <http://linux.die.net/man/1/top>`__).
+ other than executable code. It matches "top"'s DATA column).
- **lib** *(Linux)*: the memory used by shared libraries.
@@ -1584,9 +1525,8 @@ Process class
- **pageins** *(macOS)*: number of actual pageins.
- For on explanation of Windows fields rely on
- `PROCESS_MEMORY_COUNTERS_EX <http://msdn.microsoft.com/en-us/library/windows/desktop/ms684874(v=vs.85).aspx>`__ structure doc.
- Example on Linux:
+ For on explanation of Windows fields rely on `PROCESS_MEMORY_COUNTERS_EX`_
+ structure doc. Example on Linux:
>>> import psutil
>>> p = psutil.Process()
@@ -1643,8 +1583,7 @@ Process class
pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0)
>>>
- See also `procsmem.py <https://github.com/giampaolo/psutil/blob/master/scripts/procsmem.py>`__
- for an example application.
+ See also `procsmem.py`_ for an example application.
.. versionadded:: 4.0.0
@@ -1672,8 +1611,7 @@ Process class
is ``False`` each mapped region is shown as a single entity and the
named tuple will also include the mapped region's address space (*addr*)
and permission set (*perms*).
- See `pmap.py <https://github.com/giampaolo/psutil/blob/master/scripts/pmap.py>`__
- for an example application.
+ See `pmap.py`_ for an example application.
+---------------+---------+--------------+-----------+
| Linux | Windows | FreeBSD | Solaris |
@@ -1752,16 +1690,13 @@ Process class
- **position** (*Linux*): the file (offset) position.
- **mode** (*Linux*): a string indicating how the file was opened, similarly
- `open <https://docs.python.org/3/library/functions.html#open>`__'s
- ``mode`` argument. Possible values are ``'r'``, ``'w'``, ``'a'``,
- ``'r+'`` and ``'a+'``. There's no distinction between files opened in
- bynary or text mode (``"b"`` or ``"t"``).
+ to `open`_ builtin ``mode`` argument.
+ Possible values are ``'r'``, ``'w'``, ``'a'``, ``'r+'`` and ``'a+'``.
+ There's no distinction between files opened in binary or text mode
+ (``"b"`` or ``"t"``).
- **flags** (*Linux*): the flags which were passed to the underlying
- `os.open <https://docs.python.org/3/library/os.html#os.open>`__ C call
- when the file was opened (e.g.
- `os.O_RDONLY <https://docs.python.org/3/library/os.html#os.O_RDONLY>`__,
- `os.O_TRUNC <https://docs.python.org/3/library/os.html#os.O_TRUNC>`__,
- etc).
+ `os.open`_ C call when the file was opened (e.g. `os.O_RDONLY`_,
+ `os.O_TRUNC`_, etc).
>>> import psutil
>>> f = open('file.ext', 'w')
@@ -1798,17 +1733,12 @@ Process class
To get system-wide connections use :func:`psutil.net_connections()`.
Every named tuple provides 6 attributes:
- - **fd**: the socket file descriptor. This can be passed to
- `socket.fromfd() <http://docs.python.org/library/socket.html#socket.fromfd>`__
- to obtain a usable socket object.
- On Windows, FreeBSD and SunOS this is always set to ``-1``.
- - **family**: the address family, either `AF_INET
- <http://docs.python.org//library/socket.html#socket.AF_INET>`__,
- `AF_INET6 <http://docs.python.org//library/socket.html#socket.AF_INET6>`__
- or `AF_UNIX <http://docs.python.org//library/socket.html#socket.AF_UNIX>`__.
- - **type**: the address type, either
- `SOCK_STREAM <http://docs.python.org//library/socket.html#socket.SOCK_STREAM>`__ or
- `SOCK_DGRAM <http://docs.python.org//library/socket.html#socket.SOCK_DGRAM>`__.
+ - **fd**: the socket file descriptor. This can be passed to `socket.fromfd`_
+ to obtain a usable socket object. On Windows, FreeBSD and SunOS this is
+ always set to ``-1``.
+ - **family**: the address family, either `AF_INET`_, `AF_INET6`_ or
+ `AF_UNIX`_.
+ - **type**: the address type, either `SOCK_STREAM`_ or `SOCK_DGRAM`_.
- **laddr**: the local address as a ``(ip, port)`` named tuple or a ``path``
in case of AF_UNIX sockets. For UNIX sockets see notes below.
- **raddr**: the remote address as a ``(ip, port)`` named tuple or an
@@ -1891,9 +1821,8 @@ Process class
.. method:: send_signal(signal)
- Send a signal to process (see
- `signal module <http://docs.python.org//library/signal.html>`__
- constants) preemptively checking whether PID has been reused.
+ Send a signal to process (see `signal module`_ constants) preemptively
+ checking whether PID has been reused.
On UNIX this is the same as ``os.kill(pid, sig)``.
On Windows only *SIGTERM*, *CTRL_C_EVENT* and *CTRL_BREAK_EVENT* signals
are supported and *SIGTERM* is treated as an alias for :meth:`kill()`.
@@ -1932,8 +1861,7 @@ Process class
Kill the current process by using *SIGKILL* signal preemptively
checking whether PID has been reused.
On UNIX this is the same as ``os.kill(pid, signal.SIGKILL)``.
- On Windows this is done by using
- `TerminateProcess <http://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx>`__.
+ On Windows this is done by using `TerminateProcess`_.
See also how to `kill a process tree <#kill-process-tree>`__ and
`terminate my children <#terminate-my-children>`__.
@@ -1960,10 +1888,9 @@ Popen class
.. class:: Popen(*args, **kwargs)
- A more convenient interface to stdlib
- `subprocess.Popen <http://docs.python.org/library/subprocess.html#subprocess.Popen>`__.
+ A more convenient interface to stdlib `subprocess.Popen`_.
It starts a sub process and you deal with it exactly as when using
- `subprocess.Popen <http://docs.python.org/library/subprocess.html#subprocess.Popen>`__
+ `subprocess.Popen`_.
but in addition it also provides all the methods of :class:`psutil.Process`
class.
For method names common to both classes such as
@@ -1971,18 +1898,16 @@ Popen class
:meth:`terminate() <psutil.Process.terminate()>` and
:meth:`kill() <psutil.Process.kill()>`
:class:`psutil.Process` implementation takes precedence.
- For a complete documentation refer to
- `subprocess module documentation <http://docs.python.org/library/subprocess.html>`__.
+ For a complete documentation refer to subprocess module documentation.
.. note::
- Unlike `subprocess.Popen <http://docs.python.org/library/subprocess.html#subprocess.Popen>`__
- this class preemptively checks whether PID has been reused on
+ Unlike `subprocess.Popen`_ this class preemptively checks whether PID has
+ been reused on
:meth:`send_signal() <psutil.Process.send_signal()>`,
:meth:`terminate() <psutil.Process.terminate()>` and
:meth:`kill() <psutil.Process.kill()>`
- so that you can't accidentally terminate another process, fixing
- http://bugs.python.org/issue6973.
+ so that you can't accidentally terminate another process, fixing `BPO-6973`_.
>>> import psutil
>>> from subprocess import PIPE
@@ -2138,10 +2063,7 @@ Constants
``"/proc"``).
You may want to re-set this constant right after importing psutil in case
your /proc filesystem is mounted elsewhere or if you want to retrieve
- information about Linux containers such as
- `Docker <https://www.docker.io/>`__,
- `Heroku <https://www.heroku.com/>`__ or
- `LXC <https://linuxcontainers.org/>`__ (see
+ information about Linux containers such as Docker, Heroku or LXC (see
`here <https://fabiokung.com/2014/03/13/memory-inside-linux-containers/>`__
for more info).
It must be noted that this trick works only for APIs which rely on /proc
@@ -2204,8 +2126,7 @@ Constants
.. data:: REALTIME_PRIORITY_CLASS
A set of integers representing the priority of a process on Windows (see
- `MSDN documentation <http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx>`__).
- They can be used in conjunction with
+ `SetPriorityClass`_). They can be used in conjunction with
:meth:`psutil.Process.nice()` to get or set process priority.
Availability: Windows
@@ -2231,10 +2152,8 @@ Constants
*IOPRIO_CLASS_IDLE* means the process will get I/O time when no-one else
needs the disk.
For further information refer to manuals of
- `ionice <http://linux.die.net/man/1/ionice>`__
- command line utility or
- `ioprio_get <http://linux.die.net/man/2/ioprio_get>`__
- system call.
+ `ionice <http://linux.die.net/man/1/ionice>`__ command line utility or
+ `ioprio_get`_ system call.
Availability: Linux
@@ -2263,8 +2182,8 @@ Constants
.. data:: RLIMIT_STACK
Constants used for getting and setting process resource limits to be used in
- conjunction with :meth:`psutil.Process.rlimit()`. See
- `man prlimit <http://linux.die.net/man/2/prlimit>`__ for further information.
+ conjunction with :meth:`psutil.Process.rlimit()`. See `man prlimit`_ for
+ further information.
Availability: Linux
@@ -2313,8 +2232,7 @@ Constants
Unicode
=======
-Starting from version 5.3.0 psutil adds unicode support, see
-`issue #1040 <https://github.com/giampaolo/psutil/issues/1040>`__.
+Starting from version 5.3.0 psutil adds unicode support, see `issue #1040`_.
The notes below apply to *any* API returning a string such as
:meth:`Process.exe` or :meth:`Process.cwd`, including non-filesystem related
methods such as :meth:`Process.username` or :meth:`WindowsService.description`:
@@ -2591,8 +2509,7 @@ FAQs
* Q: Why do I get :class:`AccessDenied` for certain processes?
* A: This may happen when you query processess owned by another user,
- especially on `macOS <https://github.com/giampaolo/psutil/issues/883>`__ and
- Windows.
+ especially on macOS (see `issue #883`_) and Windows.
Unfortunately there's not much you can do about this except running the
Python process with higher privileges.
On Unix you may run the the Python process as root or use the SUID bit
@@ -2605,8 +2522,7 @@ FAQs
* Q: What about load average?
* A: psutil does not expose any load average function as it's already available
- in python as
- `os.getloadavg <https://docs.python.org/3/library/os.html#os.getloadavg>`__.
+ in python as `os.getloadavg`_.
Running tests
=============
@@ -2624,8 +2540,7 @@ Development guide
=================
If you plan on hacking on psutil (e.g. want to add a new feature or fix a bug)
-take a look at the
-`development guide <https://github.com/giampaolo/psutil/blob/master/DEVGUIDE.rst>`_.
+take a look at the `development guide`_.
Timeline
========
@@ -2914,3 +2829,61 @@ Timeline
`0.1.0 <https://pypi.org/project/psutil/0.1.0/#files>`__ -
`what's new <https://github.com/giampaolo/psutil/blob/master/HISTORY.rst#010>`__ -
`diff <https://github.com/giampaolo/psutil/compare/d84cc9a783d977368a64016cdb3568d2c9bceacc...release-0.1.0#files_bucket>`__
+
+
+.. _`AF_INET6`: https://docs.python.org/3/library/socket.html#socket.AF_INET6
+.. _`AF_INET`: https://docs.python.org/3/library/socket.html#socket.AF_INET
+.. _`AF_UNIX`: https://docs.python.org/3/library/socket.html#socket.AF_UNIX
+.. _`battery.py`: https://github.com/giampaolo/psutil/blob/master/scripts/battery.py
+.. _`BPO-10784`: https://bugs.python.org/issue10784
+.. _`BPO-12442`: https://bugs.python.org/issue12442
+.. _`BPO-6973`: https://bugs.python.org/issue6973
+.. _`CPU affinity`: https://www.linuxjournal.com/article/6799?page=0,0
+.. _`cpu_distribution.py`: https://github.com/giampaolo/psutil/blob/master/scripts/cpu_distribution.py
+.. _`development guide`: https://github.com/giampaolo/psutil/blob/master/DEVGUIDE.rst
+.. _`disk_usage.py`: https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py
+.. _`enums`: https://docs.python.org/3/library/enum.html#module-enum
+.. _`fans.py`: https://github.com/giampaolo/psutil/blob/master/scripts/fans.py
+.. _`GetDriveType`: https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-getdrivetypea
+.. _`getfsstat`: http://www.manpagez.com/man/2/getfsstat/
+.. _`GetPriorityClass`: https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getpriorityclass
+.. _`hash`: https://docs.python.org/3/library/functions.html#hash
+.. _`ifconfig.py`: https://github.com/giampaolo/psutil/blob/master/scripts/ifconfig.py
+.. _`ioprio_get`: https://linux.die.net/man/2/ioprio_get
+.. _`iostats doc`: https://www.kernel.org/doc/Documentation/iostats.txt
+.. _`iotop.py`: https://github.com/giampaolo/psutil/blob/master/scripts/iotop.py
+.. _`issue #1007`: https://github.com/giampaolo/psutil/issues/1007
+.. _`issue #1040`: https://github.com/giampaolo/psutil/issues/1040
+.. _`issue #883`: https://github.com/giampaolo/psutil/issues/883
+.. _`man prlimit`: https://linux.die.net/man/2/prlimit
+.. _`meminfo.py`: https://github.com/giampaolo/psutil/blob/master/scripts/meminfo.py
+.. _`netstat.py`: https://github.com/giampaolo/psutil/blob/master/scripts/netstat.py.
+.. _`nettop.py`: https://github.com/giampaolo/psutil/blob/master/scripts/nettop.py
+.. _`open`: https://docs.python.org/3/library/functions.html#open
+.. _`os.cpu_count`: https://docs.python.org/3/library/os.html#os.cpu_count
+.. _`os.getloadavg`: https://docs.python.org/3/library/os.html#os.getloadavg
+.. _`os.getpid`: https://docs.python.org/3/library/os.html#os.getpid
+.. _`os.getpriority`: https://docs.python.org/3/library/os.html#os.getpriority
+.. _`os.getresgid`: https://docs.python.org//library/os.html#os.getresgid
+.. _`os.getresuid`: https://docs.python.org//library/os.html#os.getresuid
+.. _`os.O_RDONLY`: https://docs.python.org/3/library/os.html#os.O_RDONLY
+.. _`os.O_TRUNC`: https://docs.python.org/3/library/os.html#os.O_TRUNC
+.. _`os.open`: https://docs.python.org/3/library/os.html#os.open
+.. _`os.setpriority`: https://docs.python.org/3/library/os.html#os.setpriority
+.. _`os.times`: https://docs.python.org//library/os.html#os.times
+.. _`pmap.py`: https://github.com/giampaolo/psutil/blob/master/scripts/pmap.py
+.. _`PROCESS_MEMORY_COUNTERS_EX`: https://docs.microsoft.com/en-us/windows/desktop/api/psapi/ns-psapi-_process_memory_counters_ex
+.. _`procsmem.py`: https://github.com/giampaolo/psutil/blob/master/scripts/procsmem.py
+.. _`resource.getrlimit`: https://docs.python.org/3/library/resource.html#resource.getrlimit
+.. _`resource.setrlimit`: https://docs.python.org/3/library/resource.html#resource.setrlimit
+.. _`sensors.py`: https://github.com/giampaolo/psutil/blob/master/scripts/sensors.py
+.. _`set`: https://docs.python.org/3/library/stdtypes.html#types-set.
+.. _`SetPriorityClass`: https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-setpriorityclass
+.. _`shutil.disk_usage`: https://docs.python.org/3/library/shutil.html#shutil.disk_usage.
+.. _`signal module`: https://docs.python.org//library/signal.html
+.. _`SOCK_DGRAM`: https://docs.python.org/3/library/socket.html#socket.SOCK_DGRAM
+.. _`SOCK_STREAM`: https://docs.python.org/3/library/socket.html#socket.SOCK_STREAM
+.. _`socket.fromfd`: https://docs.python.org/3/library/socket.html#socket.fromfd
+.. _`subprocess.Popen`: https://docs.python.org/3/library/subprocess.html#subprocess.Popen
+.. _`temperatures.py`: https://github.com/giampaolo/psutil/blob/master/scripts/temperatures.py
+.. _`TerminateProcess`: https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-terminateprocess
diff --git a/psutil/__init__.py b/psutil/__init__.py
index 9c6bf2bd..ab2ed349 100644
--- a/psutil/__init__.py
+++ b/psutil/__init__.py
@@ -1417,7 +1417,7 @@ class Popen(Process):
http://bugs.python.org/issue6973.
For a complete documentation refer to:
- http://docs.python.org/library/subprocess.html
+ http://docs.python.org/3/library/subprocess.html
"""
def __init__(self, *args, **kwargs):
diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py
index 13c87c65..3aebbcbd 100644
--- a/psutil/tests/__init__.py
+++ b/psutil/tests/__init__.py
@@ -80,7 +80,7 @@ __all__ = [
'ThreadTask'
# test utils
'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
- 'retry_before_failing',
+ 'retry_on_failure',
# install utils
'install_pip', 'install_test_deps',
# fs utils
@@ -119,7 +119,7 @@ PYPY = '__pypy__' in sys.builtin_module_names
# --- configurable defaults
-# how many times retry_before_failing() decorator will retry
+# how many times retry_on_failure() decorator will retry
NO_RETRIES = 10
# bytes tolerance for system-wide memory related tests
MEMORY_TOLERANCE = 500 * 1024 # 500KB
@@ -607,7 +607,7 @@ class retry(object):
timeout=None,
retries=None,
interval=0.001,
- logfun=print,
+ logfun=None,
):
if timeout and retries:
raise ValueError("timeout and retries args are mutually exclusive")
@@ -814,11 +814,15 @@ class TestCase(unittest.TestCase):
unittest.TestCase = TestCase
-def retry_before_failing(retries=NO_RETRIES):
+def retry_on_failure(retries=NO_RETRIES):
"""Decorator which runs a test function and retries N times before
actually failing.
"""
- return retry(exception=AssertionError, timeout=None, retries=retries)
+ def logfun(exc):
+ print("%r, retrying" % exc, file=sys.stderr)
+
+ return retry(exception=AssertionError, timeout=None, retries=retries,
+ logfun=logfun)
def skip_on_access_denied(only_if=None):
diff --git a/psutil/tests/runner.py b/psutil/tests/runner.py
index c009e258..3fc5e05f 100755
--- a/psutil/tests/runner.py
+++ b/psutil/tests/runner.py
@@ -5,7 +5,8 @@
# found in the LICENSE file.
"""
-Unit test runner, providing colourized output.
+Unit test runner, providing colourized output and printing failures
+on KeyboardInterrupt.
"""
from __future__ import print_function
@@ -55,7 +56,7 @@ def hilite(s, color, bold=False):
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
-class ColouredResult(unittest.TextTestResult):
+class ColouredResult(TextTestResult):
def addSuccess(self, test):
TestResult.addSuccess(self, test)
@@ -74,7 +75,7 @@ class ColouredResult(unittest.TextTestResult):
self.stream.writeln(hilite("skipped: %s" % reason, BROWN))
def printErrorList(self, flavour, errors):
- flavour = hilite(flavour, RED)
+ flavour = hilite(flavour, RED, bold=flavour == 'ERROR')
TextTestResult.printErrorList(self, flavour, errors)
@@ -84,8 +85,7 @@ class ColouredRunner(TextTestRunner):
def _makeResult(self):
# Store result instance so that it can be accessed on
# KeyboardInterrupt.
- self.result = self.resultclass(
- self.stream, self.descriptions, self.verbosity)
+ self.result = TextTestRunner._makeResult(self)
return self.result
@@ -120,8 +120,8 @@ def run(name=None):
runner = ColouredRunner(verbosity=VERBOSITY)
try:
result = runner.run(get_suite(name))
- except (SystemExit, KeyboardInterrupt):
- print("received KeyboardInterrupt", file=sys.stderr)
+ except (KeyboardInterrupt, SystemExit) as err:
+ print("received %s" % err.__class__.__name__, file=sys.stderr)
runner.result.printErrors()
sys.exit(1)
else:
diff --git a/psutil/tests/test_bsd.py b/psutil/tests/test_bsd.py
index f1b5775a..5df8ad29 100755
--- a/psutil/tests/test_bsd.py
+++ b/psutil/tests/test_bsd.py
@@ -24,7 +24,7 @@ from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import MEMORY_TOLERANCE
from psutil.tests import reap_children
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import sh
from psutil.tests import unittest
from psutil.tests import which
@@ -171,7 +171,7 @@ class FreeBSDSpecificTestCase(unittest.TestCase):
total, used, free = (int(p) * 1024 for p in parts[1:4])
return total, used, free
- @retry_before_failing()
+ @retry_on_failure()
def test_proc_memory_maps(self):
out = sh('procstat -v %s' % self.pid)
maps = psutil.Process(self.pid).memory_maps(grouped=False)
@@ -209,7 +209,7 @@ class FreeBSDSpecificTestCase(unittest.TestCase):
self.assertEqual(gids.effective, int(egid))
self.assertEqual(gids.saved, int(sgid))
- @retry_before_failing()
+ @retry_on_failure()
def test_proc_ctx_switches(self):
tested = []
out = sh('procstat -r %s' % self.pid)
@@ -229,7 +229,7 @@ class FreeBSDSpecificTestCase(unittest.TestCase):
if len(tested) != 2:
raise RuntimeError("couldn't find lines match in procstat out")
- @retry_before_failing()
+ @retry_on_failure()
def test_proc_cpu_times(self):
tested = []
out = sh('procstat -r %s' % self.pid)
@@ -268,37 +268,37 @@ class FreeBSDSpecificTestCase(unittest.TestCase):
# --- virtual_memory(); tests against sysctl
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_active(self):
syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().active, syst,
delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_inactive(self):
syst = sysctl("vm.stats.vm.v_inactive_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().inactive, syst,
delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_wired(self):
syst = sysctl("vm.stats.vm.v_wire_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().wired, syst,
delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_cached(self):
syst = sysctl("vm.stats.vm.v_cache_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().cached, syst,
delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_free(self):
syst = sysctl("vm.stats.vm.v_free_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().free, syst,
delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_buffers(self):
syst = sysctl("vfs.bufspace")
self.assertAlmostEqual(psutil.virtual_memory().buffers, syst,
@@ -312,42 +312,42 @@ class FreeBSDSpecificTestCase(unittest.TestCase):
self.assertEqual(psutil.virtual_memory().total, num)
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
- @retry_before_failing()
+ @retry_on_failure()
def test_muse_vmem_active(self):
num = muse('Active')
self.assertAlmostEqual(psutil.virtual_memory().active, num,
delta=MEMORY_TOLERANCE)
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
- @retry_before_failing()
+ @retry_on_failure()
def test_muse_vmem_inactive(self):
num = muse('Inactive')
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
delta=MEMORY_TOLERANCE)
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
- @retry_before_failing()
+ @retry_on_failure()
def test_muse_vmem_wired(self):
num = muse('Wired')
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
delta=MEMORY_TOLERANCE)
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
- @retry_before_failing()
+ @retry_on_failure()
def test_muse_vmem_cached(self):
num = muse('Cache')
self.assertAlmostEqual(psutil.virtual_memory().cached, num,
delta=MEMORY_TOLERANCE)
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
- @retry_before_failing()
+ @retry_on_failure()
def test_muse_vmem_free(self):
num = muse('Free')
self.assertAlmostEqual(psutil.virtual_memory().free, num,
delta=MEMORY_TOLERANCE)
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
- @retry_before_failing()
+ @retry_on_failure()
def test_muse_vmem_buffers(self):
num = muse('Buffer')
self.assertAlmostEqual(psutil.virtual_memory().buffers, num,
diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py
index 6e260b99..394ce654 100755
--- a/psutil/tests/test_linux.py
+++ b/psutil/tests/test_linux.py
@@ -37,7 +37,7 @@ from psutil.tests import PYPY
from psutil.tests import pyrun
from psutil.tests import reap_children
from psutil.tests import reload_module
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import safe_rmpath
from psutil.tests import sh
from psutil.tests import skip_on_not_implemented
@@ -204,7 +204,7 @@ class TestSystemVirtualMemory(unittest.TestCase):
# 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
@unittest.skipIf(LINUX and get_free_version_info() < (3, 3, 12),
"old free version")
- @retry_before_failing()
+ @retry_on_failure()
def test_used(self):
free = free_physmem()
free_value = free.used
@@ -214,18 +214,14 @@ class TestSystemVirtualMemory(unittest.TestCase):
msg='%s %s \n%s' % (free_value, psutil_value, free.output))
@unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
- @retry_before_failing()
+ @retry_on_failure()
def test_free(self):
- # _, _, free_value, _ = free_physmem()
- # psutil_value = psutil.virtual_memory().free
- # self.assertAlmostEqual(
- # free_value, psutil_value, delta=MEMORY_TOLERANCE)
vmstat_value = vmstat('free memory') * 1024
psutil_value = psutil.virtual_memory().free
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_buffers(self):
vmstat_value = vmstat('buffer memory') * 1024
psutil_value = psutil.virtual_memory().buffers
@@ -234,7 +230,7 @@ class TestSystemVirtualMemory(unittest.TestCase):
# https://travis-ci.org/giampaolo/psutil/jobs/226719664
@unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
- @retry_before_failing()
+ @retry_on_failure()
def test_active(self):
vmstat_value = vmstat('active memory') * 1024
psutil_value = psutil.virtual_memory().active
@@ -243,14 +239,14 @@ class TestSystemVirtualMemory(unittest.TestCase):
# https://travis-ci.org/giampaolo/psutil/jobs/227242952
@unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
- @retry_before_failing()
+ @retry_on_failure()
def test_inactive(self):
vmstat_value = vmstat('inactive memory') * 1024
psutil_value = psutil.virtual_memory().inactive
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_shared(self):
free = free_physmem()
free_value = free.shared
@@ -261,7 +257,7 @@ class TestSystemVirtualMemory(unittest.TestCase):
free_value, psutil_value, delta=MEMORY_TOLERANCE,
msg='%s %s \n%s' % (free_value, psutil_value, free.output))
- @retry_before_failing()
+ @retry_on_failure()
def test_available(self):
# "free" output format has changed at some point:
# https://github.com/giampaolo/psutil/issues/538#issuecomment-147192098
@@ -512,14 +508,14 @@ class TestSystemSwapMemory(unittest.TestCase):
return self.assertAlmostEqual(
free_value, psutil_value, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_used(self):
free_value = free_swap().used
psutil_value = psutil.swap_memory().used
return self.assertAlmostEqual(
free_value, psutil_value, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_free(self):
free_value = free_swap().free
psutil_value = psutil.swap_memory().free
@@ -591,10 +587,10 @@ class TestSystemSwapMemory(unittest.TestCase):
@unittest.skipIf(not LINUX, "LINUX only")
-class TestSystemCPU(unittest.TestCase):
+class TestSystemCPUTimes(unittest.TestCase):
@unittest.skipIf(TRAVIS, "unknown failure on travis")
- def test_cpu_times(self):
+ def test_fields(self):
fields = psutil.cpu_times()._fields
kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0]
kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
@@ -611,9 +607,13 @@ class TestSystemCPU(unittest.TestCase):
else:
self.assertNotIn('guest_nice', fields)
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemCPUCountLogical(unittest.TestCase):
+
@unittest.skipIf(not os.path.exists("/sys/devices/system/cpu/online"),
"/sys/devices/system/cpu/online does not exist")
- def test_cpu_count_logical_w_sysdev_cpu_online(self):
+ def test_against_sysdev_cpu_online(self):
with open("/sys/devices/system/cpu/online") as f:
value = f.read().strip()
if "-" in str(value):
@@ -622,33 +622,23 @@ class TestSystemCPU(unittest.TestCase):
@unittest.skipIf(not os.path.exists("/sys/devices/system/cpu"),
"/sys/devices/system/cpu does not exist")
- def test_cpu_count_logical_w_sysdev_cpu_num(self):
+ def test_against_sysdev_cpu_num(self):
ls = os.listdir("/sys/devices/system/cpu")
count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None])
self.assertEqual(psutil.cpu_count(), count)
@unittest.skipIf(not which("nproc"), "nproc utility not available")
- def test_cpu_count_logical_w_nproc(self):
+ def test_against_nproc(self):
num = int(sh("nproc --all"))
self.assertEqual(psutil.cpu_count(logical=True), num)
@unittest.skipIf(not which("lscpu"), "lscpu utility not available")
- def test_cpu_count_logical_w_lscpu(self):
+ def test_against_lscpu(self):
out = sh("lscpu -p")
num = len([x for x in out.split('\n') if not x.startswith('#')])
self.assertEqual(psutil.cpu_count(logical=True), num)
- @unittest.skipIf(not which("lscpu"), "lscpu utility not available")
- def test_cpu_count_physical_w_lscpu(self):
- out = sh("lscpu -p")
- core_ids = set()
- for line in out.split('\n'):
- if not line.startswith('#'):
- fields = line.split(',')
- core_ids.add(fields[1])
- self.assertEqual(psutil.cpu_count(logical=False), len(core_ids))
-
- def test_cpu_count_logical_mocked(self):
+ def test_emulate_fallbacks(self):
import psutil._pslinux
original = psutil._pslinux.cpu_count_logical()
# Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
@@ -681,21 +671,37 @@ class TestSystemCPU(unittest.TestCase):
self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
m.called
- def test_cpu_count_physical_mocked(self):
- # Have open() return emtpy data and make sure None is returned
- # ('cause we want to mimick os.cpu_count())
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemCPUCountPhysical(unittest.TestCase):
+
+ @unittest.skipIf(not which("lscpu"), "lscpu utility not available")
+ def test_against_lscpu(self):
+ out = sh("lscpu -p")
+ core_ids = set()
+ for line in out.split('\n'):
+ if not line.startswith('#'):
+ fields = line.split(',')
+ core_ids.add(fields[1])
+ self.assertEqual(psutil.cpu_count(logical=False), len(core_ids))
+
+ def test_emulate_empty_cpuinfo(self):
with mock.patch('psutil._common.open', create=True) as m:
self.assertIsNone(psutil._pslinux.cpu_count_physical())
assert m.called
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemCPUFrequency(unittest.TestCase):
+
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
- def test_cpu_freq_no_result(self):
+ def test_emulate_no_files(self):
with mock.patch("psutil._pslinux.glob.glob", return_value=[]):
self.assertIsNone(psutil.cpu_freq())
@unittest.skipIf(TRAVIS, "fails on Travis")
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
- def test_cpu_freq_use_second_file(self):
+ def test_emulate_use_second_file(self):
# https://github.com/giampaolo/psutil/issues/981
def glob_mock(pattern):
if pattern.startswith("/sys/devices/system/cpu/cpufreq/policy"):
@@ -713,7 +719,7 @@ class TestSystemCPU(unittest.TestCase):
self.assertEqual(len(flags), 2)
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
- def test_cpu_freq_use_cpuinfo(self):
+ def test_emulate_use_cpuinfo(self):
# Emulate a case where /sys/devices/system/cpu/cpufreq* does not
# exist and /proc/cpuinfo is used instead.
def path_exists_mock(path):
@@ -742,7 +748,7 @@ class TestSystemCPU(unittest.TestCase):
reload_module(psutil)
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
- def test_cpu_freq_emulate_data(self):
+ def test_emulate_data(self):
def open_mock(name, *args, **kwargs):
if name.endswith('/scaling_cur_freq'):
return io.BytesIO(b"500000")
@@ -765,7 +771,7 @@ class TestSystemCPU(unittest.TestCase):
self.assertEqual(freq.max, 700.0)
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
- def test_cpu_freq_emulate_multi_cpu(self):
+ def test_emulate_multi_cpu(self):
def open_mock(name, *args, **kwargs):
if name.endswith('/scaling_cur_freq'):
return io.BytesIO(b"100000")
@@ -790,7 +796,7 @@ class TestSystemCPU(unittest.TestCase):
@unittest.skipIf(TRAVIS, "fails on Travis")
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
- def test_cpu_freq_no_scaling_cur_freq_file(self):
+ def test_emulate_no_scaling_cur_freq_file(self):
# See: https://github.com/giampaolo/psutil/issues/1071
def open_mock(name, *args, **kwargs):
if name.endswith('/scaling_cur_freq'):
@@ -829,11 +835,6 @@ class TestSystemCPU(unittest.TestCase):
self.assertRaises(NotImplementedError, psutil.cpu_freq)
-# =====================================================================
-# --- system CPU stats
-# =====================================================================
-
-
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUStats(unittest.TestCase):
@@ -856,9 +857,9 @@ class TestSystemCPUStats(unittest.TestCase):
@unittest.skipIf(not LINUX, "LINUX only")
-class TestSystemNetwork(unittest.TestCase):
+class TestSystemNetIfAddrs(unittest.TestCase):
- def test_net_if_addrs_ips(self):
+ def test_ips(self):
for name, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == psutil.AF_LINK:
@@ -867,7 +868,27 @@ class TestSystemNetwork(unittest.TestCase):
self.assertEqual(addr.address, get_ipv4_address(name))
# TODO: test for AF_INET6 family
- def test_net_if_stats(self):
+ # XXX - not reliable when having virtual NICs installed by Docker.
+ # @unittest.skipIf(not which('ip'), "'ip' utility not available")
+ # @unittest.skipIf(TRAVIS, "skipped on Travis")
+ # def test_net_if_names(self):
+ # out = sh("ip addr").strip()
+ # nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
+ # found = 0
+ # for line in out.split('\n'):
+ # line = line.strip()
+ # if re.search(r"^\d+:", line):
+ # found += 1
+ # name = line.split(':')[1].strip()
+ # self.assertIn(name, nics)
+ # self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
+ # pprint.pformat(nics), out))
+
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemNetIfStats(unittest.TestCase):
+
+ def test_against_ifconfig(self):
for name, stats in psutil.net_if_stats().items():
try:
out = sh("ifconfig %s" % name)
@@ -879,8 +900,12 @@ class TestSystemNetwork(unittest.TestCase):
self.assertEqual(stats.mtu,
int(re.findall(r'(?i)MTU[: ](\d+)', out)[0]))
- @retry_before_failing()
- def test_net_io_counters(self):
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemNetIOCounters(unittest.TestCase):
+
+ @retry_on_failure()
+ def test_against_ifconfig(self):
def ifconfig(nic):
ret = {}
out = sh("ifconfig %s" % name)
@@ -921,25 +946,13 @@ class TestSystemNetwork(unittest.TestCase):
self.assertAlmostEqual(
stats.dropout, ifconfig_ret['dropout'], delta=10)
- # XXX - not reliable when having virtual NICs installed by Docker.
- # @unittest.skipIf(not which('ip'), "'ip' utility not available")
- # @unittest.skipIf(TRAVIS, "skipped on Travis")
- # def test_net_if_names(self):
- # out = sh("ip addr").strip()
- # nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
- # found = 0
- # for line in out.split('\n'):
- # line = line.strip()
- # if re.search(r"^\d+:", line):
- # found += 1
- # name = line.split(':')[1].strip()
- # self.assertIn(name, nics)
- # self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
- # pprint.pformat(nics), out))
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemNetConnections(unittest.TestCase):
@mock.patch('psutil._pslinux.socket.inet_ntop', side_effect=ValueError)
@mock.patch('psutil._pslinux.supports_ipv6', return_value=False)
- def test_net_connections_ipv6_unsupported(self, supports_ipv6, inet_ntop):
+ def test_emulate_ipv6_unsupported(self, supports_ipv6, inet_ntop):
# see: https://github.com/giampaolo/psutil/issues/623
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
@@ -949,7 +962,7 @@ class TestSystemNetwork(unittest.TestCase):
pass
psutil.net_connections(kind='inet6')
- def test_net_connections_mocked(self):
+ def test_emulate_unix(self):
with mock_open_content(
'/proc/net/unix',
textwrap.dedent("""\
@@ -963,16 +976,16 @@ class TestSystemNetwork(unittest.TestCase):
# =====================================================================
-# --- system disk
+# --- system disks
# =====================================================================
@unittest.skipIf(not LINUX, "LINUX only")
-class TestSystemDisks(unittest.TestCase):
+class TestSystemDiskPartitions(unittest.TestCase):
@unittest.skipIf(not hasattr(os, 'statvfs'), "os.statvfs() not available")
@skip_on_not_implemented()
- def test_disk_partitions_and_usage(self):
+ def test_against_df(self):
# test psutil.disk_usage() and psutil.disk_partitions()
# against "df -a"
def df(path):
@@ -996,7 +1009,7 @@ class TestSystemDisks(unittest.TestCase):
if abs(usage.used - used) > 10 * 1024 * 1024:
self.fail("psutil=%s, df=%s" % (usage.used, used))
- def test_disk_partitions_mocked(self):
+ def test_zfs_fs(self):
# Test that ZFS partitions are returned.
with open("/proc/filesystems", "r") as f:
data = f.read()
@@ -1020,7 +1033,7 @@ class TestSystemDisks(unittest.TestCase):
assert ret
self.assertEqual(ret[0].fstype, 'zfs')
- def test_disk_partitions_procfs(self):
+ def test_emulate_realpath_fail(self):
# See: https://github.com/giampaolo/psutil/issues/1307
try:
with mock.patch('os.path.realpath',
@@ -1032,7 +1045,11 @@ class TestSystemDisks(unittest.TestCase):
finally:
psutil.PROCFS_PATH = "/proc"
- def test_disk_io_counters_kernel_2_4_mocked(self):
+
+@unittest.skipIf(not LINUX, "LINUX only")
+class TestSystemDiskIoCounters(unittest.TestCase):
+
+ def test_emulate_kernel_2_4(self):
# Tests /proc/diskstats parsing format for 2.4 kernels, see:
# https://github.com/giampaolo/psutil/issues/767
with mock_open_content(
@@ -1051,7 +1068,7 @@ class TestSystemDisks(unittest.TestCase):
self.assertEqual(ret.write_time, 8)
self.assertEqual(ret.busy_time, 10)
- def test_disk_io_counters_kernel_2_6_full_mocked(self):
+ def test_emulate_kernel_2_6_full(self):
# Tests /proc/diskstats parsing format for 2.6 kernels,
# lines reporting all metrics:
# https://github.com/giampaolo/psutil/issues/767
@@ -1071,7 +1088,7 @@ class TestSystemDisks(unittest.TestCase):
self.assertEqual(ret.write_time, 8)
self.assertEqual(ret.busy_time, 10)
- def test_disk_io_counters_kernel_2_6_limited_mocked(self):
+ def test_emulate_kernel_2_6_limited(self):
# Tests /proc/diskstats parsing format for 2.6 kernels,
# where one line of /proc/partitions return a limited
# amount of metrics when it bumps into a partition
@@ -1094,7 +1111,7 @@ class TestSystemDisks(unittest.TestCase):
self.assertEqual(ret.write_time, 0)
self.assertEqual(ret.busy_time, 0)
- def test_disk_io_counters_include_partitions(self):
+ def test_emulate_include_partitions(self):
# Make sure that when perdisk=True disk partitions are returned,
# see:
# https://github.com/giampaolo/psutil/pull/1313#issuecomment-408626842
@@ -1113,7 +1130,7 @@ class TestSystemDisks(unittest.TestCase):
self.assertEqual(ret['nvme0n1'].write_count, 5)
self.assertEqual(ret['nvme0n1p1'].write_count, 5)
- def test_disk_io_counters_exclude_partitions(self):
+ def test_emulate_exclude_partitions(self):
# Make sure that when perdisk=False partitions (e.g. 'sda1',
# 'nvme0n1p1') are skipped and not included in the total count.
# https://github.com/giampaolo/psutil/pull/1313#issuecomment-408626842
@@ -1144,7 +1161,7 @@ class TestSystemDisks(unittest.TestCase):
self.assertEqual(ret.read_count, 1)
self.assertEqual(ret.write_count, 5)
- def test_disk_io_counters_sysfs(self):
+ def test_emulate_use_sysfs(self):
def exists(path):
if path == '/proc/diskstats':
return False
@@ -1156,7 +1173,7 @@ class TestSystemDisks(unittest.TestCase):
wsysfs = psutil.disk_io_counters(perdisk=True)
self.assertEqual(len(wprocfs), len(wsysfs))
- def test_disk_io_counters_not_impl(self):
+ def test_emulate_not_impl(self):
def exists(path):
return False
@@ -2031,7 +2048,7 @@ class TestProcessAgainstStatus(unittest.TestCase):
value = tuple(map(int, value.split()[1:4]))
self.assertEqual(self.proc.gids(), value)
- @retry_before_failing()
+ @retry_on_failure()
def test_num_ctx_switches(self):
value = self.read_status_file("voluntary_ctxt_switches:")
self.assertEqual(self.proc.num_ctx_switches().voluntary, value)
diff --git a/psutil/tests/test_osx.py b/psutil/tests/test_osx.py
index 0e6ed67c..723b255e 100755
--- a/psutil/tests/test_osx.py
+++ b/psutil/tests/test_osx.py
@@ -17,7 +17,7 @@ from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import MEMORY_TOLERANCE
from psutil.tests import reap_children
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import sh
from psutil.tests import unittest
@@ -215,25 +215,25 @@ class TestSystemAPIs(unittest.TestCase):
sysctl_hwphymem = sysctl('sysctl hw.memsize')
self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_free(self):
vmstat_val = vm_stat("free")
psutil_val = psutil.virtual_memory().free
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_active(self):
vmstat_val = vm_stat("active")
psutil_val = psutil.virtual_memory().active
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_inactive(self):
vmstat_val = vm_stat("inactive")
psutil_val = psutil.virtual_memory().inactive
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
- @retry_before_failing()
+ @retry_on_failure()
def test_vmem_wired(self):
vmstat_val = vm_stat("wired")
psutil_val = psutil.virtual_memory().wired
@@ -241,13 +241,13 @@ class TestSystemAPIs(unittest.TestCase):
# --- swap mem
- @retry_before_failing()
+ @retry_on_failure()
def test_swapmem_sin(self):
vmstat_val = vm_stat("Pageins")
psutil_val = psutil.swap_memory().sin
self.assertEqual(psutil_val, vmstat_val)
- @retry_before_failing()
+ @retry_on_failure()
def test_swapmem_sout(self):
vmstat_val = vm_stat("Pageout")
psutil_val = psutil.swap_memory().sout
diff --git a/psutil/tests/test_posix.py b/psutil/tests/test_posix.py
index 8f7fbf51..d24abad3 100755
--- a/psutil/tests/test_posix.py
+++ b/psutil/tests/test_posix.py
@@ -29,7 +29,7 @@ from psutil.tests import HAS_NET_IO_COUNTERS
from psutil.tests import mock
from psutil.tests import PYTHON_EXE
from psutil.tests import reap_children
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import sh
from psutil.tests import skip_on_access_denied
from psutil.tests import TRAVIS
@@ -157,7 +157,7 @@ class TestProcess(unittest.TestCase):
assert fun.called
@skip_on_access_denied()
- @retry_before_failing()
+ @retry_on_failure()
def test_rss_memory(self):
# give python interpreter some time to properly initialize
# so that the results are the same
@@ -167,7 +167,7 @@ class TestProcess(unittest.TestCase):
self.assertEqual(rss_ps, rss_psutil)
@skip_on_access_denied()
- @retry_before_failing()
+ @retry_on_failure()
def test_vsz_memory(self):
# give python interpreter some time to properly initialize
# so that the results are the same
@@ -317,7 +317,7 @@ class TestProcess(unittest.TestCase):
class TestSystemAPIs(unittest.TestCase):
"""Test some system APIs."""
- @retry_before_failing()
+ @retry_on_failure()
def test_pids(self):
# Note: this test might fail if the OS is starting/killing
# other processes in the meantime
@@ -354,7 +354,7 @@ class TestSystemAPIs(unittest.TestCase):
# can't find users on APPVEYOR or TRAVIS
@unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
"unreliable on APPVEYOR or TRAVIS")
- @retry_before_failing()
+ @retry_on_failure()
def test_users(self):
out = sh("who")
lines = out.split('\n')
diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py
index baa3e346..a550809f 100755
--- a/psutil/tests/test_process.py
+++ b/psutil/tests/test_process.py
@@ -56,7 +56,7 @@ from psutil.tests import mock
from psutil.tests import PYPY
from psutil.tests import PYTHON_EXE
from psutil.tests import reap_children
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import safe_rmpath
from psutil.tests import sh
from psutil.tests import skip_on_access_denied
@@ -545,7 +545,7 @@ class TestProcess(unittest.TestCase):
self.assertEqual(athread.user_time, athread[1])
self.assertEqual(athread.system_time, athread[2])
- @retry_before_failing()
+ @retry_on_failure()
@skip_on_access_denied(only_if=MACOS)
@unittest.skipIf(not HAS_THREADS, 'not supported')
def test_threads_2(self):
diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py
index 00a38586..75e65b0f 100755
--- a/psutil/tests/test_system.py
+++ b/psutil/tests/test_system.py
@@ -44,7 +44,7 @@ from psutil.tests import HAS_SENSORS_FANS
from psutil.tests import HAS_SENSORS_TEMPERATURES
from psutil.tests import mock
from psutil.tests import reap_children
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import safe_rmpath
from psutil.tests import TESTFN
from psutil.tests import TESTFN_UNICODE
@@ -124,7 +124,7 @@ class TestSystemAPIs(unittest.TestCase):
for p in alive:
self.assertFalse(hasattr(p, 'returncode'))
- @retry_before_failing(30)
+ @retry_on_failure(30)
def test(procs, callback):
gone, alive = psutil.wait_procs(procs, timeout=0.03,
callback=callback)
@@ -143,7 +143,7 @@ class TestSystemAPIs(unittest.TestCase):
for p in alive:
self.assertFalse(hasattr(p, 'returncode'))
- @retry_before_failing(30)
+ @retry_on_failure(30)
def test(procs, callback):
gone, alive = psutil.wait_procs(procs, timeout=0.03,
callback=callback)
diff --git a/psutil/tests/test_windows.py b/psutil/tests/test_windows.py
index a9aeba8e..e0bfdbb8 100755
--- a/psutil/tests/test_windows.py
+++ b/psutil/tests/test_windows.py
@@ -26,7 +26,7 @@ from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import mock
from psutil.tests import reap_children
-from psutil.tests import retry_before_failing
+from psutil.tests import retry_on_failure
from psutil.tests import sh
from psutil.tests import unittest
@@ -137,7 +137,7 @@ class TestSystemAPIs(unittest.TestCase):
# Note: this test is not very reliable
@unittest.skipIf(APPVEYOR, "test not relieable on appveyor")
- @retry_before_failing()
+ @retry_on_failure()
def test_pids(self):
# Note: this test might fail if the OS is starting/killing
# other processes in the meantime
@@ -146,7 +146,7 @@ class TestSystemAPIs(unittest.TestCase):
psutil_pids = set(psutil.pids())
self.assertEqual(wmi_pids, psutil_pids)
- @retry_before_failing()
+ @retry_on_failure()
def test_disks(self):
ps_parts = psutil.disk_partitions(all=True)
wmi_parts = wmi.WMI().Win32_LogicalDisk()