Commit a53a068c authored by Jondy Zhao's avatar Jondy Zhao

Add snapshot of psutil-0.6.1

parent 3f0f7a79
Intro
=====
We would like to recognize some of the people who have been instrumental in the
development of psutil.
I'm sure we are forgetting some people (feel free to email us), but here is a
short list.
It's modeled after the Linux CREDITS file where the fields are:
name (N), e-mail (E), web-address (W), country (C), description (D), (I) issues
(issue tracker is at http://code.google.com/p/psutil/issues/list).
Really thanks to all of you.
Maintainers
===========
N: Giampaolo Rodola'
C: Italy
E: g.rodola@gmail.com
N: Jay Loden
C: NJ, USA
E: jloden@gmail.com
W: http://www.jayloden.com
Contributors
============
N: Jeremy Whitlock
E: jcscoobyrs@gmail.com
I: 125, 150, 174, 206
N: wj32
E: wj32.64@gmail.com
D: process username() and get_connections() on Windows
I: 114, 115
N: Yan Raber
C: Bologna, Italy
E: yanraber@gmail.com
D: help on Windows development
N: Dave Daeschler
C: USA
E: david.daeschler@gmail.com
D: initial design/bootstrap and continuing bug fixes
N: cjgohlke
E: cjgohlke@gmail.com
D: Windows 64 bit support
I: 107
N: Jeffery Kline
E: jeffery.kline@gmail.com
I: 130
N: Grabriel Monnerat
E: gabrielmonnerat@gmail.com
I: 146
N: Philip Roberts
E: philip.roberts@gmail.com
I: 168
N: jcscoobyrs
E: jcscoobyrs@gmail.com
I: 125
N: Sandro Tosi
E: sandro.tosi@gmail.com
I: 200, 201
N: Andrew Colin
E: andrew.colin@gmail.com
I: 248
N: Amoser
E: amoser@google.com
I: 266, 267
N: Matthew Grant
E: matthewgrant5@gmail.com
I: 271
N: oweidner
E: oweidner@cct.lsu.edu
I: 275
N: Tarek Ziade
E: ziade.tarek
I: 281
N: Luca Cipriani
C: Turin, Italy
E: luca.opensource@gmail.com
I: 278
N: Maciej Lach,
E: maciej.lach@gmail.com
I: 294
N: James Pye
E: james.pye@gmail.com
I: 305, 306
N: Stanchev Emil
E: stanchev.emil
I: 314
N: Kim Gräsman
E: kim.grasman@gmail.com
D: ...also kindly donated some money.
I: 316
N: Riccardo Murri
C: Italy
I: 318
This diff is collapsed.
==================
Using easy_install
==================
The easiest way to install psutil from sources is using easy_install.
Get the latest easy_install version from http://pypi.python.org/pypi/setuptools
and just run:
easy_install psutil
This should get the most updated psutil version from the Python pypi repository,
unpack it, compile it and install it automatically.
===================================
Installing on Windows using mingw32
===================================
After the mingw [1] environment is properly set up on your system you can
compile Windows sources by entering:
setup.py build -c mingw32
To compile and install just append the "install" keyword at the end of the
command line above, like this:
setup.py build -c mingw32 install
It might be possible that distutils will complain about missing gcc executable.
That means you have to add mingw bin PATH variable first.
Entering this line in the command prompt should do the work:
SET PATH=C:\MinGW\bin;%PATH%
NOTE: this assumes MinGW is installed in C:\MinGW, if not simply replace the
path in the command above with an appropriate location.
[1] http://www.mingw.org/
=========================================
Installing on Windows using Visual Studio
=========================================
To use Visual Studio to install psutil, you must have the same version of
Visual Studio used to compile your installation of Python. For older versions
of Python that will be Visual Studio 2003. For 2.6 and later it should be
Visual Studio 2008. If you do not have the requisite version of Visual Studio
available then it is recommended to use MinGW to compile psutil instead.
If you do have Visual Studio installed, you can use the basic distutils
commands:
setup.py build
...or to install and build:
setup.py install
distutils should take care of any necessary magic to compile from there.
==================
Installing on OS X
==================
OS X installation from source will require gcc which you can obtain as part of
the 'XcodeTools' installer from Apple. Then you can run the standard distutils
commands.
To build only:
python setup.py build
To install and build:
python setup.py install
NOTE: due to developer's hardware limitations psutil has only been compiled and
tested on OS X 10.4.11 so may or may not work on other versions.
=====================
Installing on FreeBSD
=====================
The same compiler used to install Python must be present on the system in order
to build modules using distutils. Assuming it is installed, you can build using
the standard distutils commands.
Build only:
python setup.py build
Install and build:
python setup.py install
===================
Installing on Linux
===================
gcc is required and so the python headers. They can easily be installed by using
the distro package manager. For example, on Ubuntu:
sudo apt-get install python-dev
Once done, you can install/build psutil with:
python setup.py install
psutil is distributed under BSD license reproduced below.
Copyright (c) 2009, Jay Loden, Dave Daeschler, Giampaolo Rodola'
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the psutil authors nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include CREDITS
include HISTORY
include LICENSE
include MANIFEST.in
include README
include setup.py
recursive-include psutil *.py *.c *.h
recursive-include test *.py
recursive-include examples *.py
Metadata-Version: 1.1
Name: psutil
Version: 0.6.1
Summary: A process and system utilities module for Python
Home-page: http://code.google.com/p/psutil/
Author: Giampaolo Rodola
Author-email: g.rodola <at> gmail <dot> com
License: License :: OSI Approved :: BSD License
Download-URL: http://psutil.googlecode.com/files/psutil-0.6.1.tar.gz
Description: ===========
Quick links
===========
* `Home page <http://code.google.com/p/psutil>`_
* `Download <http://code.google.com/p/psutil/downloads/list>`_
* `Documentation <http://code.google.com/p/psutil/wiki/Documentation>`_
=======
Summary
=======
psutil is a module providing an interface for retrieving information on all
running processes and system utilization (CPU, memory, disks, network, users) in
a portable way by using Python, implementing many functionalities offered by
command line tools such as: **ps, top, df, kill, free, lsof, free, netstat,
ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
**32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
a single code base.
==============
Example usages
==============
CPU
===
>>> import psutil
>>> psutil.cpu_times()
cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
iowait=629.509, irq=0.0, softirq=19.422)
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1)
...
4.0
5.9
3.8
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1, percpu=True)
...
[4.0, 6.9]
[7.0, 8.5]
[1.2, 9.0]
>>>
Memory
======
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L,
free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L,
cached=1251086336)
>>> psutil.swap_memory()
swap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1,
sin=304193536, sout=677842944)
>>>
Disks
=====
>>> psutil.disk_partitions()
[partition(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
partition(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
>>>
>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
>>>
>>> psutil.disk_io_counters()
iostat(read_count=719566, write_count=1082197, read_bytes=18626220032,
write_bytes=24081764352, read_time=5023392, write_time=63199568)
>>>
Network
=======
>>> psutil.network_io_counters(pernic=True)
{'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
packets_sent=453698, packets_recv=453698),
'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
packets_sent=3605828, packets_recv=4096685)}
>>>
Users
=====
>>> psutil.get_users()
[user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
>>>
Process management
==================
>>> import psutil
>>> psutil.get_pid_list()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
>>>
>>> p = psutil.Process(7055)
>>> p.name
'python'
>>> p.exe
'/usr/bin/python'
>>> p.getcwd()
'/home/giampaolo'
>>> p.cmdline
['/usr/bin/python', 'main.py']
>>>
>>> str(p.status)
'running'
>>> p.username
'giampaolo'
>>> p.create_time
1267551141.5019531
>>> p.terminal
'/dev/pts/0'
>>>
>>> p.uids
user(real=1000, effective=1000, saved=1000)
>>> p.gids
group(real=1000, effective=1000, saved=1000)
>>>
>>> p.get_cpu_times()
cputimes(user=1.02, system=0.31)
>>> p.get_cpu_percent(interval=1.0)
12.1
>>> p.get_cpu_affinity()
[0, 1, 2, 3]
>>> p.set_cpu_affinity([0])
>>>
>>> p.get_memory_percent()
0.63423
>>>
>>> p.get_memory_info()
meminfo(rss=7471104, vms=68513792)
>>> p.get_ext_memory_info()
meminfo(rss=9662464, vms=49192960, shared=3612672, text=2564096, lib=0, data=5754880, dirty=0)
>>> p.get_memory_maps()
[mmap(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
mmap(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
mmap(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=34124, anonymous=1245, swap=0),
mmap(path='[heap]', rss=54653, anonymous=8192, swap=0),
mmap(path='[stack]', rss=1542, anonymous=166, swap=0),
...]
>>>
>>> p.get_io_counters()
io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
>>>
>>> p.get_open_files()
[openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
>>>
>>> p.get_connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
remote_address=('72.14.234.100', 80), status='CLOSING'),
connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
remote_address=('72.14.234.83', 443), status='SYN_SENT')]
>>>
>>> p.get_num_threads()
4
>>> p.get_num_fds()
8
>>> p.get_threads()
[thread(id=5234, user_time=22.5, system_time=9.2891),
thread(id=5235, user_time=0.0, system_time=0.0),
thread(id=5236, user_time=0.0, system_time=0.0),
thread(id=5237, user_time=0.0707, system_time=1.1)]
>>>
>>> p.get_num_ctx_switches()
amount(voluntary=78, involuntary=19)
>>>
>>> p.get_nice()
0
>>> p.set_nice(10)
>>>
>>> p.suspend()
>>> p.resume()
>>>
>>> p.terminate()
>>> p.wait(timeout=3)
0
>>>
>>> psutil.test()
USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
root 1 0.0 0.0 24584 2240 ? Jun17 00:00 init
root 2 0.0 0.0 0 0 ? Jun17 00:00 kthreadd
root 3 0.0 0.0 0 0 ? Jun17 00:05 ksoftirqd/0
...
giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
giampaolo 31721 0.0 2.2 773060 181896 ? 00:04 10:30 chrome
root 31763 0.0 0.0 0 0 ? 00:05 00:00 kworker/0:1
>>>
Keywords: ps,top,kill,free,lsof,netstat,nice,tty,ionice,uptime,taskmgr,process,df,iotop,iostat,ifconfig,taskset,who,pidof,pmap,smem,monitoring
Platform: Platform Independent
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft
Classifier: Operating System :: Microsoft :: Windows :: Windows NT/2000
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: POSIX :: BSD :: FreeBSD
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: C
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.4
Classifier: Programming Language :: Python :: 2.5
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.0
Classifier: Programming Language :: Python :: 3.1
Classifier: Programming Language :: Python :: 3.2
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Networking
Classifier: Topic :: System :: Networking :: Monitoring
Classifier: Topic :: System :: Benchmark
Classifier: Topic :: System :: Hardware
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: Utilities
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: BSD License
===========
Quick links
===========
* `Home page <http://code.google.com/p/psutil>`_
* `Download <http://code.google.com/p/psutil/downloads/list>`_
* `Documentation <http://code.google.com/p/psutil/wiki/Documentation>`_
=======
Summary
=======
psutil is a module providing an interface for retrieving information on all
running processes and system utilization (CPU, memory, disks, network, users) in
a portable way by using Python, implementing many functionalities offered by
command line tools such as: **ps, top, df, kill, free, lsof, free, netstat,
ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
**32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
a single code base.
==============
Example usages
==============
CPU
===
>>> import psutil
>>> psutil.cpu_times()
cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
iowait=629.509, irq=0.0, softirq=19.422)
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1)
...
4.0
5.9
3.8
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1, percpu=True)
...
[4.0, 6.9]
[7.0, 8.5]
[1.2, 9.0]
>>>
Memory
======
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L,
free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L,
cached=1251086336)
>>> psutil.swap_memory()
swap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1,
sin=304193536, sout=677842944)
>>>
Disks
=====
>>> psutil.disk_partitions()
[partition(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
partition(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
>>>
>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
>>>
>>> psutil.disk_io_counters()
iostat(read_count=719566, write_count=1082197, read_bytes=18626220032,
write_bytes=24081764352, read_time=5023392, write_time=63199568)
>>>
Network
=======
>>> psutil.network_io_counters(pernic=True)
{'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
packets_sent=453698, packets_recv=453698),
'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
packets_sent=3605828, packets_recv=4096685)}
>>>
Users
=====
>>> psutil.get_users()
[user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
>>>
Process management
==================
>>> import psutil
>>> psutil.get_pid_list()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
>>>
>>> p = psutil.Process(7055)
>>> p.name
'python'
>>> p.exe
'/usr/bin/python'
>>> p.getcwd()
'/home/giampaolo'
>>> p.cmdline
['/usr/bin/python', 'main.py']
>>>
>>> str(p.status)
'running'
>>> p.username
'giampaolo'
>>> p.create_time
1267551141.5019531
>>> p.terminal
'/dev/pts/0'
>>>
>>> p.uids
user(real=1000, effective=1000, saved=1000)
>>> p.gids
group(real=1000, effective=1000, saved=1000)
>>>
>>> p.get_cpu_times()
cputimes(user=1.02, system=0.31)
>>> p.get_cpu_percent(interval=1.0)
12.1
>>> p.get_cpu_affinity()
[0, 1, 2, 3]
>>> p.set_cpu_affinity([0])
>>>
>>> p.get_memory_percent()
0.63423
>>>
>>> p.get_memory_info()
meminfo(rss=7471104, vms=68513792)
>>> p.get_ext_memory_info()
meminfo(rss=9662464, vms=49192960, shared=3612672, text=2564096, lib=0, data=5754880, dirty=0)
>>> p.get_memory_maps()
[mmap(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
mmap(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
mmap(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=34124, anonymous=1245, swap=0),
mmap(path='[heap]', rss=54653, anonymous=8192, swap=0),
mmap(path='[stack]', rss=1542, anonymous=166, swap=0),
...]
>>>
>>> p.get_io_counters()
io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
>>>
>>> p.get_open_files()
[openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
>>>
>>> p.get_connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
remote_address=('72.14.234.100', 80), status='CLOSING'),
connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
remote_address=('72.14.234.83', 443), status='SYN_SENT')]
>>>
>>> p.get_num_threads()
4
>>> p.get_num_fds()
8
>>> p.get_threads()
[thread(id=5234, user_time=22.5, system_time=9.2891),
thread(id=5235, user_time=0.0, system_time=0.0),
thread(id=5236, user_time=0.0, system_time=0.0),
thread(id=5237, user_time=0.0707, system_time=1.1)]
>>>
>>> p.get_num_ctx_switches()
amount(voluntary=78, involuntary=19)
>>>
>>> p.get_nice()
0
>>> p.set_nice(10)
>>>
>>> p.suspend()
>>> p.resume()
>>>
>>> p.terminate()
>>> p.wait(timeout=3)
0
>>>
>>> psutil.test()
USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
root 1 0.0 0.0 24584 2240 ? Jun17 00:00 init
root 2 0.0 0.0 0 0 ? Jun17 00:00 kthreadd
root 3 0.0 0.0 0 0 ? Jun17 00:05 ksoftirqd/0
...
giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
giampaolo 31721 0.0 2.2 773060 181896 ? 00:04 10:30 chrome
root 31763 0.0 0.0 0 0 ? 00:05 00:00 kworker/0:1
>>>
#!/usr/bin/env python
#
# $Id: disk_usage.py 1340 2012-06-09 13:42:21Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
List all mounted disk partitions a-la "df -h" command.
"""
import sys
import psutil
from psutil._compat import print_
def bytes2human(n):
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
# '9.8K'
# >>> bytes2human(100001221)
# '95.4M'
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
def main():
templ = "%-17s %8s %8s %8s %5s%% %9s %s"
print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
for part in psutil.disk_partitions(all=False):
usage = psutil.disk_usage(part.mountpoint)
print_(templ % (part.device,
bytes2human(usage.total),
bytes2human(usage.used),
bytes2human(usage.free),
int(usage.percent),
part.fstype,
part.mountpoint))
if __name__ == '__main__':
sys.exit(main())
#!/usr/bin/env python
#
# $Id: free.py 1508 2012-08-13 12:30:07Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
A clone of 'free' cmdline utility.
"""
import psutil
from psutil._compat import print_
def main():
virt = psutil.virtual_memory()
swap = psutil.swap_memory()
templ = "%-7s %10s %10s %10s %10s %10s %10s"
print_(templ % ('', 'total', 'used', 'free', 'shared', 'buffers', 'cache'))
print_(templ % ('Mem:', int(virt.total / 1024),
int(virt.used / 1024),
int(virt.free / 1024),
int(getattr(virt, 'shared', 0) / 1024),
int(getattr(virt, 'buffers', 0) / 1024),
int(getattr(virt, 'cached', 0) / 1024)))
print_(templ % ('Swap:', int(swap.total / 1024),
int(swap.used / 1024),
int(swap.free / 1024),
'', '', ''))
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: iotop.py 1236 2011-12-13 19:00:35Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
A clone of iotop (http://guichaz.free.fr/iotop/) showing real time
disk I/O statistics.
It works on Linux only (FreeBSD and OSX are missing support for IO
counters).
It doesn't work on Windows as curses module is required.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
"""
import os
import sys
import psutil
if not hasattr(psutil.Process, 'get_io_counters') or os.name != 'posix':
sys.exit('platform not supported')
import time
import curses
import atexit
# --- curses stuff
def tear_down():
win.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
win = curses.initscr()
atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
try:
if highlight:
line += " " * (win.getmaxyx()[1] - len(line))
win.addstr(lineno, 0, line, curses.A_REVERSE)
else:
win.addstr(lineno, 0, line, 0)
except curses.error:
lineno = 0
win.refresh()
raise
else:
lineno += 1
# --- /curses stuff
def bytes2human(n):
"""
>>> bytes2human(10000)
'9.8 K/s'
>>> bytes2human(100001221)
'95.4 M/s'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s/s' % (value, s)
return '%.2f B/s' % (n)
def poll(interval):
"""Calculate IO usage by comparing IO statics before and
after the interval.
Return a tuple including all currently running processes
sorted by IO activity and total disks I/O activity.
"""
# first get a list of all processes and disk io counters
procs = [p for p in psutil.process_iter()]
for p in procs[:]:
try:
p._before = p.get_io_counters()
except psutil.Error:
procs.remove(p)
continue
disks_before = psutil.disk_io_counters()
# sleep some time
time.sleep(interval)
# then retrieve the same info again
for p in procs[:]:
try:
p._after = p.get_io_counters()
p._cmdline = ' '.join(p.cmdline)
if not p._cmdline:
p._cmdline = p.name
p._username = p.username
except psutil.NoSuchProcess:
procs.remove(p)
disks_after = psutil.disk_io_counters()
# finally calculate results by comparing data before and
# after the interval
for p in procs:
p._read_per_sec = p._after.read_bytes - p._before.read_bytes
p._write_per_sec = p._after.write_bytes - p._before.write_bytes
p._total = p._read_per_sec + p._write_per_sec
disks_read_per_sec = disks_after.read_bytes - disks_before.read_bytes
disks_write_per_sec = disks_after.write_bytes - disks_before.write_bytes
# sort processes by total disk IO so that the more intensive
# ones get listed first
processes = sorted(procs, key=lambda p: p._total, reverse=True)
return (processes, disks_read_per_sec, disks_write_per_sec)
def refresh_window(procs, disks_read, disks_write):
"""Print results on screen by using curses."""
curses.endwin()
templ = "%-5s %-7s %11s %11s %s"
win.erase()
disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \
% (bytes2human(disks_read), bytes2human(disks_write))
print_line(disks_tot)
header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
print_line(header, highlight=True)
for p in procs:
line = templ % (p.pid,
p._username[:7],
bytes2human(p._read_per_sec),
bytes2human(p._write_per_sec),
p._cmdline)
try:
print_line(line)
except curses.error:
break
win.refresh()
def main():
try:
interval = 0
while 1:
args = poll(interval)
refresh_window(*args)
interval = 1
except (KeyboardInterrupt, SystemExit):
pass
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: killall.py 1143 2011-10-05 19:11:59Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
Kill a process by name.
"""
import os
import sys
import psutil
def main():
if len(sys.argv) != 2:
sys.exit('usage: %s name' % __file__)
else:
NAME = sys.argv[1]
killed = []
for proc in psutil.process_iter():
if proc.name == NAME and proc.pid != os.getpid():
proc.kill()
killed.append(proc.pid)
if not killed:
sys.exit('%s: no process found' % NAME)
else:
sys.exit(0)
sys.exit(main())
#!/usr/bin/env python
#
# $Id: meminfo.py 1509 2012-08-13 12:31:18Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
Print system memory information.
"""
import psutil
from psutil._compat import print_
def to_meg(n):
return str(int(n / 1024 / 1024)) + "M"
def pprint_ntuple(nt):
for name in nt._fields:
value = getattr(nt, name)
if name != 'percent':
value = to_meg(value)
print_('%-10s : %7s' % (name.capitalize(), value))
def main():
print_('MEMORY\n------')
pprint_ntuple(psutil.virtual_memory())
print_('\nSWAP\n----')
pprint_ntuple(psutil.swap_memory())
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: netstat.py 1457 2012-07-14 18:09:36Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
A clone of 'netstat'.
"""
import socket
from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
import psutil
from psutil._compat import print_
AD = "-"
AF_INET6 = getattr(socket, 'AF_INET6', object())
proto_map = {(AF_INET, SOCK_STREAM) : 'tcp',
(AF_INET6, SOCK_STREAM) : 'tcp6',
(AF_INET, SOCK_DGRAM) : 'udp',
(AF_INET6, SOCK_DGRAM) : 'udp6'}
def main():
templ = "%-5s %-22s %-22s %-13s %-6s %s"
print_(templ % ("Proto", "Local addr", "Remote addr", "Status", "PID",
"Program name"))
for p in psutil.process_iter():
name = '?'
try:
name = p.name
cons = p.get_connections(kind='inet')
except psutil.AccessDenied:
print_(templ % (AD, AD, AD, AD, p.pid, name))
else:
for c in cons:
raddr = ""
laddr = "%s:%s" % (c.local_address)
if c.remote_address:
raddr = "%s:%s" % (c.remote_address)
print_(templ % (proto_map[(c.family, c.type)],
laddr,
raddr,
str(c.status),
p.pid,
name[:15]))
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: iotop.py 1160 2011-10-14 18:50:36Z g.rodola@gmail.com $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
Shows real-time network statistics.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
"""
import sys
import os
if os.name != 'posix':
sys.exit('platform not supported')
import curses
import atexit
import time
import psutil
# --- curses stuff
def tear_down():
win.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
win = curses.initscr()
atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
try:
if highlight:
line += " " * (win.getmaxyx()[1] - len(line))
win.addstr(lineno, 0, line, curses.A_REVERSE)
else:
win.addstr(lineno, 0, line, 0)
except curses.error:
lineno = 0
win.refresh()
raise
else:
lineno += 1
# --- curses stuff
def bytes2human(n):
"""
>>> bytes2human(10000)
'9.8 K'
>>> bytes2human(100001221)
'95.4 M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s' % (value, s)
return '%.2f B' % (n)
def poll(interval):
"""Retrieve raw stats within an interval window."""
tot_before = psutil.network_io_counters()
pnic_before = psutil.network_io_counters(pernic=True)
# sleep some time
time.sleep(interval)
tot_after = psutil.network_io_counters()
pnic_after = psutil.network_io_counters(pernic=True)
return (tot_before, tot_after, pnic_before, pnic_after)
def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
"""Print stats on screen."""
global lineno
# totals
print_line("total bytes: sent: %-10s received: %s" \
% (bytes2human(tot_after.bytes_sent),
bytes2human(tot_after.bytes_recv))
)
print_line("total packets: sent: %-10s received: %s" \
% (tot_after.packets_sent, tot_after.packets_recv)
)
# per-network interface details: let's sort network interfaces so
# that the ones which generated more traffic are shown first
print_line("")
nic_names = list(pnic_after.keys())
nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
for name in nic_names:
stats_before = pnic_before[name]
stats_after = pnic_after[name]
templ = "%-15s %15s %15s"
print_line(templ % (name, "TOTAL", "PER-SEC"), highlight=True)
print_line(templ % (
"bytes-sent",
bytes2human(stats_after.bytes_sent),
bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
))
print_line(templ % (
"bytes-recv",
bytes2human(stats_after.bytes_recv),
bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
))
print_line(templ % (
"pkts-sent",
stats_after.packets_sent,
stats_after.packets_sent - stats_before.packets_sent,
))
print_line(templ % (
"pkts-recv",
stats_after.packets_recv,
stats_after.packets_recv - stats_before.packets_recv,
))
print_line("")
win.refresh()
lineno = 0
def main():
try:
interval = 0
while 1:
args = poll(interval)
refresh_window(*args)
interval = 1
except (KeyboardInterrupt, SystemExit):
pass
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: pmap.py 1420 2012-07-08 12:12:01Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
A clone of 'pmap' utility on Linux, 'vmmap' on OSX and 'procstat -v' on BSD.
Report memory map of a process.
"""
import sys
import psutil
from psutil._compat import print_
def main():
if len(sys.argv) != 2:
sys.exit('usage: pmap pid')
p = psutil.Process(int(sys.argv[1]))
print_("pid=%s, name=%s" % (p.pid, p.name))
templ = "%-16s %10s %-7s %s"
print_(templ % ("Address", "RSS", "Mode", "Mapping"))
total_rss = 0
for m in p.get_memory_maps(grouped=False):
total_rss += m.rss
print_(templ % (m.addr.split('-')[0].zfill(16),
str(m.rss / 1024) + 'K' ,
m.perms,
m.path))
print_("-" * 33)
print_(templ % ("Total", str(total_rss / 1024) + 'K', '', ''))
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: process_detail.py 1498 2012-07-24 21:41:28Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
Print detailed information about a process.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
"""
import os
import datetime
import socket
import sys
import psutil
def convert_bytes(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
def print_(a, b):
if sys.stdout.isatty() and os.name == 'posix':
fmt = '\x1b[1;32m%-17s\x1b[0m %s' %(a, b)
else:
fmt = '%-15s %s' %(a, b)
# python 2/3 compatibility layer
sys.stdout.write(fmt + '\n')
sys.stdout.flush()
def run(pid):
ACCESS_DENIED = ''
try:
p = psutil.Process(pid)
pinfo = p.as_dict(ad_value=ACCESS_DENIED)
except psutil.NoSuchProcess:
sys.exit(str(sys.exc_info()[1]))
try:
if p.parent:
parent = '(%s)' % p.parent.name
else:
parent = ''
except psutil.Error:
parent = ''
started = datetime.datetime.fromtimestamp(pinfo['create_time']
).strftime('%Y-%M-%d %H:%M')
io = pinfo.get('io_counters', None)
mem = '%s%% (resident=%s, virtual=%s) ' % (
round(pinfo['memory_percent'], 1),
convert_bytes(pinfo['memory_info'].rss),
convert_bytes(pinfo['memory_info'].vms))
children = p.get_children()
print_('pid', pinfo['pid'])
print_('name', pinfo['name'])
print_('exe', pinfo['exe'])
print_('parent', '%s %s' % (pinfo['ppid'], parent))
print_('cmdline', ' '.join(pinfo['cmdline']))
print_('started', started)
print_('user', pinfo['username'])
if os.name == 'posix':
print_('uids', 'real=%s, effective=%s, saved=%s' % pinfo['uids'])
print_('gids', 'real=%s, effective=%s, saved=%s' % pinfo['gids'])
print_('terminal', pinfo['terminal'] or '')
if hasattr(p, 'getcwd'):
print_('cwd', pinfo['cwd'])
print_('memory', mem)
print_('cpu', '%s%% (user=%s, system=%s)' % (pinfo['cpu_percent'],
pinfo['cpu_times'].user,
pinfo['cpu_times'].system))
print_('status', pinfo['status'])
print_('niceness', pinfo['nice'])
print_('num threads', pinfo['num_threads'])
if io != ACCESS_DENIED:
print_('I/O', 'bytes-read=%s, bytes-written=%s' % \
(convert_bytes(io.read_bytes),
convert_bytes(io.write_bytes)))
if children:
print_('children', '')
for child in children:
print_('', 'pid=%s name=%s' % (child.pid, child.name))
if pinfo['open_files'] != ACCESS_DENIED:
print_('open files', '')
for file in pinfo['open_files']:
print_('', 'fd=%s %s ' % (file.fd, file.path))
if pinfo['threads']:
print_('running threads', '')
for thread in pinfo['threads']:
print_('', 'id=%s, user-time=%s, sys-time=%s' \
% (thread.id, thread.user_time, thread.system_time))
if pinfo['connections'] != ACCESS_DENIED:
print_('open connections', '')
for conn in pinfo['connections']:
if conn.type == socket.SOCK_STREAM:
type = 'TCP'
elif conn.type == socket.SOCK_DGRAM:
type = 'UDP'
else:
type = 'UNIX'
lip, lport = conn.local_address
if not conn.remote_address:
rip, rport = '*', '*'
else:
rip, rport = conn.remote_address
print_('', '%s:%s -> %s:%s type=%s status=%s' \
% (lip, lport, rip, rport, type, conn.status))
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) == 1:
sys.exit(run(os.getpid()))
elif len(argv) == 2:
sys.exit(run(int(argv[1])))
else:
sys.exit('usage: %s [pid]' % __file__)
if __name__ == '__main__':
sys.exit(main())
#!/usr/bin/env python
#
# $Id: top.py 1498 2012-07-24 21:41:28Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
A clone of top / htop.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
"""
import os
import sys
if os.name != 'posix':
sys.exit('platform not supported')
import time
import curses
import atexit
from datetime import datetime, timedelta
import psutil
# --- curses stuff
def tear_down():
win.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
win = curses.initscr()
atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
try:
if highlight:
line += " " * (win.getmaxyx()[1] - len(line))
win.addstr(lineno, 0, line, curses.A_REVERSE)
else:
win.addstr(lineno, 0, line, 0)
except curses.error:
lineno = 0
win.refresh()
raise
else:
lineno += 1
# --- /curses stuff
def bytes2human(n):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = int(float(n) / prefix[s])
return '%s%s' % (value, s)
return "%sB" % n
def poll(interval):
# sleep some time
time.sleep(interval)
procs = []
procs_status = {}
for p in psutil.process_iter():
try:
p.dict = p.as_dict(['username', 'get_nice', 'get_memory_info',
'get_memory_percent', 'get_cpu_percent',
'get_cpu_times', 'name', 'status'])
try:
procs_status[str(p.dict['status'])] += 1
except KeyError:
procs_status[str(p.dict['status'])] = 1
except psutil.NoSuchProcess:
pass
else:
procs.append(p)
# return processes sorted by CPU percent usage
processes = sorted(procs, key=lambda p: p.dict['cpu_percent'], reverse=True)
return (processes, procs_status)
def print_header(procs_status, num_procs):
"""Print system-related info, above the process list."""
def get_dashes(perc):
dashes = "|" * int((float(perc) / 10 * 4))
empty_dashes = " " * (40 - len(dashes))
return dashes, empty_dashes
# cpu usage
for cpu_num, perc in enumerate(psutil.cpu_percent(interval=0, percpu=True)):
dashes, empty_dashes = get_dashes(perc)
print_line(" CPU%-2s [%s%s] %5s%%" % (cpu_num, dashes, empty_dashes,
perc))
mem = psutil.virtual_memory()
dashes, empty_dashes = get_dashes(mem.percent)
used = mem.total - mem.available
line = " Mem [%s%s] %5s%% %6s/%s" % (
dashes, empty_dashes,
mem.percent,
str(int(used / 1024 / 1024)) + "M",
str(int(mem.total / 1024 / 1024)) + "M"
)
print_line(line)
# swap usage
swap = psutil.swap_memory()
dashes, empty_dashes = get_dashes(swap.percent)
line = " Swap [%s%s] %5s%% %6s/%s" % (
dashes, empty_dashes,
swap.percent,
str(int(swap.used / 1024 / 1024)) + "M",
str(int(swap.total / 1024 / 1024)) + "M"
)
print_line(line)
# processes number and status
st = []
for x, y in procs_status.items():
if y:
st.append("%s=%s" % (x, y))
st.sort(key=lambda x: x[:3] in ('run', 'sle'), reverse=1)
print_line(" Processes: %s (%s)" % (num_procs, ' '.join(st)))
# load average, uptime
uptime = datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME)
av1, av2, av3 = os.getloadavg()
line = " Load average: %.2f %.2f %.2f Uptime: %s" \
% (av1, av2, av3, str(uptime).split('.')[0])
print_line(line)
def refresh_window(procs, procs_status):
"""Print results on screen by using curses."""
curses.endwin()
templ = "%-6s %-8s %4s %5s %5s %6s %4s %9s %2s"
win.erase()
header = templ % ("PID", "USER", "NI", "VIRT", "RES", "CPU%", "MEM%",
"TIME+", "NAME")
print_header(procs_status, len(procs))
print_line("")
print_line(header, highlight=True)
for p in procs:
# TIME+ column shows process CPU cumulative time and it
# is expressed as: "mm:ss.ms"
if p.dict['cpu_times'] != None:
ctime = timedelta(seconds=sum(p.dict['cpu_times']))
ctime = "%s:%s.%s" % (ctime.seconds // 60 % 60,
str((ctime.seconds % 60)).zfill(2),
str(ctime.microseconds)[:2])
else:
ctime = ''
if p.dict['memory_percent'] is not None:
p.dict['memory_percent'] = round(p.dict['memory_percent'], 1)
else:
p.dict['memory_percent'] = ''
if p.dict['cpu_percent'] is None:
p.dict['cpu_percent'] = ''
line = templ % (p.pid,
p.dict['username'][:8],
p.dict['nice'],
bytes2human(getattr(p.dict['memory_info'], 'vms', 0)),
bytes2human(getattr(p.dict['memory_info'], 'rss', 0)),
p.dict['cpu_percent'],
p.dict['memory_percent'],
ctime,
p.dict['name'] or '',
)
try:
print_line(line)
except curses.error:
break
win.refresh()
def main():
try:
interval = 0
while 1:
args = poll(interval)
refresh_window(*args)
interval = 1
except (KeyboardInterrupt, SystemExit):
pass
if __name__ == '__main__':
main()
#!/usr/bin/env python
#
# $Id: who.py 1340 2012-06-09 13:42:21Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""
A clone of 'who' command; print information about users who are
currently logged in.
"""
import sys
from datetime import datetime
import psutil
from psutil._compat import print_
def main():
users = psutil.get_users()
for user in users:
print_("%-15s %-15s %s (%s)" % \
(user.name,
user.terminal or '-',
datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"),
user.host)
)
if __name__ == '__main__':
main()
Metadata-Version: 1.1
Name: psutil
Version: 0.6.1
Summary: A process and system utilities module for Python
Home-page: http://code.google.com/p/psutil/
Author: Giampaolo Rodola
Author-email: g.rodola <at> gmail <dot> com
License: License :: OSI Approved :: BSD License
Download-URL: http://psutil.googlecode.com/files/psutil-0.6.1.tar.gz
Description: ===========
Quick links
===========
* `Home page <http://code.google.com/p/psutil>`_
* `Download <http://code.google.com/p/psutil/downloads/list>`_
* `Documentation <http://code.google.com/p/psutil/wiki/Documentation>`_
=======
Summary
=======
psutil is a module providing an interface for retrieving information on all
running processes and system utilization (CPU, memory, disks, network, users) in
a portable way by using Python, implementing many functionalities offered by
command line tools such as: **ps, top, df, kill, free, lsof, free, netstat,
ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
**32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
a single code base.
==============
Example usages
==============
CPU
===
>>> import psutil
>>> psutil.cpu_times()
cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
iowait=629.509, irq=0.0, softirq=19.422)
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1)
...
4.0
5.9
3.8
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1, percpu=True)
...
[4.0, 6.9]
[7.0, 8.5]
[1.2, 9.0]
>>>
Memory
======
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L,
free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L,
cached=1251086336)
>>> psutil.swap_memory()
swap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1,
sin=304193536, sout=677842944)
>>>
Disks
=====
>>> psutil.disk_partitions()
[partition(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
partition(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
>>>
>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
>>>
>>> psutil.disk_io_counters()
iostat(read_count=719566, write_count=1082197, read_bytes=18626220032,
write_bytes=24081764352, read_time=5023392, write_time=63199568)
>>>
Network
=======
>>> psutil.network_io_counters(pernic=True)
{'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
packets_sent=453698, packets_recv=453698),
'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
packets_sent=3605828, packets_recv=4096685)}
>>>
Users
=====
>>> psutil.get_users()
[user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
>>>
Process management
==================
>>> import psutil
>>> psutil.get_pid_list()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
>>>
>>> p = psutil.Process(7055)
>>> p.name
'python'
>>> p.exe
'/usr/bin/python'
>>> p.getcwd()
'/home/giampaolo'
>>> p.cmdline
['/usr/bin/python', 'main.py']
>>>
>>> str(p.status)
'running'
>>> p.username
'giampaolo'
>>> p.create_time
1267551141.5019531
>>> p.terminal
'/dev/pts/0'
>>>
>>> p.uids
user(real=1000, effective=1000, saved=1000)
>>> p.gids
group(real=1000, effective=1000, saved=1000)
>>>
>>> p.get_cpu_times()
cputimes(user=1.02, system=0.31)
>>> p.get_cpu_percent(interval=1.0)
12.1
>>> p.get_cpu_affinity()
[0, 1, 2, 3]
>>> p.set_cpu_affinity([0])
>>>
>>> p.get_memory_percent()
0.63423
>>>
>>> p.get_memory_info()
meminfo(rss=7471104, vms=68513792)
>>> p.get_ext_memory_info()
meminfo(rss=9662464, vms=49192960, shared=3612672, text=2564096, lib=0, data=5754880, dirty=0)
>>> p.get_memory_maps()
[mmap(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
mmap(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
mmap(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=34124, anonymous=1245, swap=0),
mmap(path='[heap]', rss=54653, anonymous=8192, swap=0),
mmap(path='[stack]', rss=1542, anonymous=166, swap=0),
...]
>>>
>>> p.get_io_counters()
io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
>>>
>>> p.get_open_files()
[openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
>>>
>>> p.get_connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
remote_address=('72.14.234.100', 80), status='CLOSING'),
connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
remote_address=('72.14.234.83', 443), status='SYN_SENT')]
>>>
>>> p.get_num_threads()
4
>>> p.get_num_fds()
8
>>> p.get_threads()
[thread(id=5234, user_time=22.5, system_time=9.2891),
thread(id=5235, user_time=0.0, system_time=0.0),
thread(id=5236, user_time=0.0, system_time=0.0),
thread(id=5237, user_time=0.0707, system_time=1.1)]
>>>
>>> p.get_num_ctx_switches()
amount(voluntary=78, involuntary=19)
>>>
>>> p.get_nice()
0
>>> p.set_nice(10)
>>>
>>> p.suspend()
>>> p.resume()
>>>
>>> p.terminate()
>>> p.wait(timeout=3)
0
>>>
>>> psutil.test()
USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
root 1 0.0 0.0 24584 2240 ? Jun17 00:00 init
root 2 0.0 0.0 0 0 ? Jun17 00:00 kthreadd
root 3 0.0 0.0 0 0 ? Jun17 00:05 ksoftirqd/0
...
giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
giampaolo 31721 0.0 2.2 773060 181896 ? 00:04 10:30 chrome
root 31763 0.0 0.0 0 0 ? 00:05 00:00 kworker/0:1
>>>
Keywords: ps,top,kill,free,lsof,netstat,nice,tty,ionice,uptime,taskmgr,process,df,iotop,iostat,ifconfig,taskset,who,pidof,pmap,smem,monitoring
Platform: Platform Independent
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft
Classifier: Operating System :: Microsoft :: Windows :: Windows NT/2000
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: POSIX :: BSD :: FreeBSD
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: C
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.4
Classifier: Programming Language :: Python :: 2.5
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.0
Classifier: Programming Language :: Python :: 3.1
Classifier: Programming Language :: Python :: 3.2
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Networking
Classifier: Topic :: System :: Networking :: Monitoring
Classifier: Topic :: System :: Benchmark
Classifier: Topic :: System :: Hardware
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: Utilities
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: BSD License
CREDITS
HISTORY
INSTALL
LICENSE
MANIFEST.in
README
setup.py
examples/disk_usage.py
examples/free.py
examples/iotop.py
examples/killall.py
examples/meminfo.py
examples/netstat.py
examples/nettop.py
examples/pmap.py
examples/process_detail.py
examples/top.py
examples/who.py
psutil/__init__.py
psutil/_common.py
psutil/_compat.py
psutil/_psbsd.py
psutil/_pslinux.py
psutil/_psmswindows.py
psutil/_psosx.py
psutil/_psposix.py
psutil/_psutil_bsd.c
psutil/_psutil_bsd.h
psutil/_psutil_common.c
psutil/_psutil_common.h
psutil/_psutil_linux.c
psutil/_psutil_linux.h
psutil/_psutil_mswindows.c
psutil/_psutil_mswindows.h
psutil/_psutil_osx.c
psutil/_psutil_osx.h
psutil/_psutil_posix.c
psutil/_psutil_posix.h
psutil/error.py
psutil.egg-info/PKG-INFO
psutil.egg-info/SOURCES.txt
psutil.egg-info/dependency_links.txt
psutil.egg-info/top_level.txt
psutil/arch/bsd/process_info.c
psutil/arch/bsd/process_info.h
psutil/arch/mswindows/ntextapi.h
psutil/arch/mswindows/process_handles.c
psutil/arch/mswindows/process_handles.h
psutil/arch/mswindows/process_info.c
psutil/arch/mswindows/process_info.h
psutil/arch/mswindows/security.c
psutil/arch/mswindows/security.h
psutil/arch/osx/process_info.c
psutil/arch/osx/process_info.h
test/_bsd.py
test/_linux.py
test/_osx.py
test/_posix.py
test/_windows.py
test/test_memory_leaks.py
test/test_psutil.py
\ No newline at end of file
psutil
_psutil_linux
_psutil_posix
This diff is collapsed.
#/usr/bin/env python
#
#$Id: _common.py 1524 2012-08-16 15:06:32Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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 all _ps* modules."""
from __future__ import division
import sys
import os
import stat
import errno
import warnings
from psutil._compat import namedtuple, long, wraps
# --- functions
def usage_percent(used, total, _round=None):
"""Calculate percentage usage of 'used' against 'total'."""
try:
ret = (used / total) * 100
except ZeroDivisionError:
ret = 0
if _round is not None:
return round(ret, _round)
else:
return ret
class constant(int):
"""A constant type; overrides base int to provide a useful name on str()."""
def __new__(cls, value, name, doc=None):
inst = super(constant, cls).__new__(cls, value)
inst._name = name
if doc is not None:
inst.__doc__ = doc
return inst
def __str__(self):
return self._name
def __eq__(self, other):
# Use both int or str values when comparing for equality
# (useful for serialization):
# >>> st = constant(0, "running")
# >>> st == 0
# True
# >>> st == 'running'
# True
if isinstance(other, int):
return int(self) == other
if isinstance(other, long):
return long(self) == other
if isinstance(other, str):
return self._name == other
return False
def __ne__(self, other):
return not self.__eq__(other)
def memoize(f):
"""A simple memoize decorator for functions."""
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf
class cached_property(object):
"""A memoize decorator for class properties."""
enabled = True
def __init__(self, func):
self.func = func
def __get__(self, instance, type):
ret = self.func(instance)
if self.enabled:
instance.__dict__[self.func.__name__] = ret
return ret
# http://goo.gl/jYLvf
def deprecated(replacement=None):
"""A decorator which can be used to mark functions as deprecated."""
def outer(fun):
msg = "psutil.%s is deprecated" % fun.__name__
if replacement is not None:
msg += "; use %s instead" % replacement
if fun.__doc__ is None:
fun.__doc__ = msg
@wraps(fun)
def inner(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return fun(*args, **kwargs)
return inner
return outer
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:
err = sys.exc_info()[1]
if err.errno in (errno.EPERM, errno.EACCES):
raise
return False
else:
return stat.S_ISREG(st.st_mode)
# --- constants
STATUS_RUNNING = constant(0, "running")
STATUS_SLEEPING = constant(1, "sleeping")
STATUS_DISK_SLEEP = constant(2, "disk sleep")
STATUS_STOPPED = constant(3, "stopped")
STATUS_TRACING_STOP = constant(4, "tracing stop")
STATUS_ZOMBIE = constant(5, "zombie")
STATUS_DEAD = constant(6, "dead")
STATUS_WAKE_KILL = constant(7, "wake kill")
STATUS_WAKING = constant(8, "waking")
STATUS_IDLE = constant(9, "idle") # BSD
STATUS_LOCKED = constant(10, "locked") # BSD
STATUS_WAITING = constant(11, "waiting") # BSD
# --- Process.get_connections() 'kind' parameter mapping
import socket
from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
AF_INET6 = getattr(socket, 'AF_INET6', None)
AF_UNIX = getattr(socket, 'AF_UNIX', None)
conn_tmap = {
"all" : ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
"tcp" : ([AF_INET, AF_INET6], [SOCK_STREAM]),
"tcp4" : ([AF_INET], [SOCK_STREAM]),
"udp" : ([AF_INET, AF_INET6], [SOCK_DGRAM]),
"udp4" : ([AF_INET], [SOCK_DGRAM]),
"inet" : ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
"inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
"inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
}
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]),
})
del AF_INET, AF_INET6, AF_UNIX, SOCK_STREAM, SOCK_DGRAM, socket
# --- namedtuples
# system
nt_sys_cputimes = namedtuple('cputimes', 'user nice system idle iowait irq softirq')
nt_sysmeminfo = namedtuple('usage', 'total used free percent')
# XXX - would 'available' be better than 'free' as for virtual_memory() nt?
nt_swapmeminfo = namedtuple('swap', 'total used free percent sin sout')
nt_diskinfo = namedtuple('usage', 'total used free percent')
nt_partition = namedtuple('partition', 'device mountpoint fstype opts')
nt_net_iostat = namedtuple('iostat',
'bytes_sent bytes_recv packets_sent packets_recv errin errout dropin dropout')
nt_disk_iostat = namedtuple('iostat', 'read_count write_count read_bytes write_bytes read_time write_time')
nt_user = namedtuple('user', 'name terminal host started')
# processes
nt_meminfo = namedtuple('meminfo', 'rss vms')
nt_cputimes = namedtuple('cputimes', 'user system')
nt_openfile = namedtuple('openfile', 'path fd')
nt_connection = namedtuple('connection', 'fd family type local_address remote_address status')
nt_thread = namedtuple('thread', 'id user_time system_time')
nt_uids = namedtuple('user', 'real effective saved')
nt_gids = namedtuple('group', 'real effective saved')
nt_io = namedtuple('io', 'read_count write_count read_bytes write_bytes')
nt_ionice = namedtuple('ionice', 'ioclass value')
nt_ctxsw = namedtuple('amount', 'voluntary involuntary')
#!/usr/bin/env python
#
# $Id: _compat.py 1524 2012-08-16 15:06:32Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""Module which provides compatibility with older Python versions."""
__all__ = ["PY3", "int", "long", "xrange", "exec_", "callable",
"namedtuple", "property", "defaultdict"]
import sys
# --- python 2/3 compatibility layer
PY3 = sys.version_info >= (3,)
try:
import __builtin__
except ImportError:
import builtins as __builtin__ # py3
if PY3:
int = int
long = int
xrange = range
exec_ = getattr(__builtin__, "exec")
print_ = getattr(__builtin__, "print")
else:
int = int
long = long
xrange = xrange
def exec_(code, globs=None, locs=None):
if globs is None:
frame = _sys._getframe(1)
globs = frame.f_globals
if locs is None:
locs = frame.f_locals
del frame
elif locs is None:
locs = globs
exec("""exec code in globs, locs""")
def print_(s):
sys.stdout.write(s + '\n')
sys.stdout.flush()
# removed in 3.0, reintroduced in 3.2
try:
callable = callable
except Exception:
def callable(obj):
for klass in type(obj).__mro__:
if "__call__" in klass.__dict__:
return True
return False
# --- stdlib additions
try:
from collections import namedtuple
except ImportError:
from operator import itemgetter as _itemgetter
from keyword import iskeyword as _iskeyword
import sys as _sys
def namedtuple(typename, field_names, verbose=False, rename=False):
"""A collections.namedtuple implementation written in Python
to support Python versions < 2.6.
Taken from: http://code.activestate.com/recipes/500261/
"""
# Parse and validate the field names. Validation serves two
# purposes, generating informative error messages and preventing
# template injection attacks.
if isinstance(field_names, basestring):
# names separated by whitespace and/or commas
field_names = field_names.replace(',', ' ').split()
field_names = tuple(map(str, field_names))
if rename:
names = list(field_names)
seen = set()
for i, name in enumerate(names):
if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
or not name or name[0].isdigit() or name.startswith('_')
or name in seen):
names[i] = '_%d' % i
seen.add(name)
field_names = tuple(names)
for name in (typename,) + field_names:
if not min(c.isalnum() or c=='_' for c in name):
raise ValueError('Type names and field names can only contain ' \
'alphanumeric characters and underscores: %r'
% name)
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a keyword: %r' \
% name)
if name[0].isdigit():
raise ValueError('Type names and field names cannot start with a ' \
'number: %r' % name)
seen_names = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: %r'
% name)
if name in seen_names:
raise ValueError('Encountered duplicate field name: %r' % name)
seen_names.add(name)
# Create and fill-in the class template
numfields = len(field_names)
# tuple repr without parens or quotes
argtxt = repr(field_names).replace("'", "")[1:-1]
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
template = '''class %(typename)s(tuple):
'%(typename)s(%(argtxt)s)' \n
__slots__ = () \n
_fields = %(field_names)r \n
def __new__(_cls, %(argtxt)s):
return _tuple.__new__(_cls, (%(argtxt)s)) \n
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new %(typename)s object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != %(numfields)d:
raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
return result \n
def __repr__(self):
return '%(typename)s(%(reprtxt)s)' %% self \n
def _asdict(self):
'Return a new dict which maps field names to their values'
return dict(zip(self._fields, self)) \n
def _replace(_self, **kwds):
'Return a new %(typename)s object replacing specified fields with new values'
result = _self._make(map(kwds.pop, %(field_names)r, _self))
if kwds:
raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
return result \n
def __getnewargs__(self):
return tuple(self) \n\n''' % locals()
for i, name in enumerate(field_names):
template += ' %s = _property(_itemgetter(%d))\n' % (name, i)
if verbose:
sys.stdout.write(template + '\n')
sys.stdout.flush()
# Execute the template string in a temporary namespace
namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
_property=property, _tuple=tuple)
try:
exec_(template, namespace)
except SyntaxError:
e = sys.exc_info()[1]
raise SyntaxError(e.message + ':\n' + template)
result = namespace[typename]
# For pickling to work, the __module__ variable needs to be set
# to the frame where the named tuple is created. Bypass this
# step in enviroments where sys._getframe is not defined (Jython
# for example) or sys._getframe is not defined for arguments
# greater than 0 (IronPython).
try:
result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return result
# hack to support property.setter/deleter on python < 2.6
# http://docs.python.org/library/functions.html?highlight=property#property
if hasattr(property, 'setter'):
property = property
else:
class property(__builtin__.property):
__metaclass__ = type
def __init__(self, fget, *args, **kwargs):
super(property, self).__init__(fget, *args, **kwargs)
self.__doc__ = fget.__doc__
def getter(self, method):
return property(method, self.fset, self.fdel)
def setter(self, method):
return property(self.fget, method, self.fdel)
def deleter(self, method):
return property(self.fget, self.fset, method)
# py 2.5 collections.defauldict
# Taken from:
# http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/
# credits: Jason Kirtland
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not hasattr(default_factory, '__call__')):
raise TypeError('first argument must be callable')
dict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'defaultdict(%s, %s)' % (self.default_factory,
dict.__repr__(self))
# py 2.5 functools.wraps
try:
from functools import wraps
except ImportError:
def wraps(original):
def inner(fn):
# see functools.WRAPPER_ASSIGNMENTS
for attribute in ['__module__',
'__name__',
'__doc__'
]:
setattr(fn, attribute, getattr(original, attribute))
# see functools.WRAPPER_UPDATES
for attribute in ['__dict__',
]:
if hasattr(fn, attribute):
getattr(fn, attribute).update(getattr(original, attribute))
else:
setattr(fn, attribute,
getattr(original, attribute).copy())
return fn
return inner
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#!/usr/bin/env python
#
# $Id: _psposix.py 1409 2012-07-04 08:21:06Z g.rodola $
#
# Copyright (c) 2009, Jay Loden, 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.
"""Routines common to all posix systems."""
import os
import errno
import psutil
import sys
import time
import glob
from psutil.error import TimeoutExpired
from psutil._common import nt_diskinfo, usage_percent
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if not isinstance(pid, int):
raise TypeError('an integer is required')
if pid < 0:
return False
try:
os.kill(pid, 0)
except OSError:
e = sys.exc_info()[1]
return e.errno == errno.EPERM
else:
return True
def wait_pid(pid, timeout=None):
"""Wait for process with pid 'pid' to terminate and return its
exit status code as an integer.
If pid is not a children of os.getpid() (current process) just
waits until the process disappears and return None.
If pid does not exist at all return None immediately.
Raise TimeoutExpired on timeout expired.
"""
def check_timeout(delay):
if timeout is not None:
if time.time() >= stop_at:
raise TimeoutExpired(pid)
time.sleep(delay)
return min(delay * 2, 0.04)
if timeout is not None:
waitcall = lambda: os.waitpid(pid, os.WNOHANG)
stop_at = time.time() + timeout
else:
waitcall = lambda: os.waitpid(pid, 0)
delay = 0.0001
while 1:
try:
retpid, status = waitcall()
except OSError:
err = sys.exc_info()[1]
if err.errno == errno.EINTR:
delay = check_timeout(delay)
continue
elif err.errno == errno.ECHILD:
# This has two meanings:
# - pid is not a child of os.getpid() in which case
# we keep polling until it's gone
# - pid never existed in the first place
# In both cases we'll eventually return None as we
# can't determine its exit status code.
while 1:
if pid_exists(pid):
delay = check_timeout(delay)
else:
return
else:
raise
else:
if retpid == 0:
# WNOHANG was used, pid is still running
delay = check_timeout(delay)
continue
# process exited due to a signal; return the integer of
# that signal
if os.WIFSIGNALED(status):
return os.WTERMSIG(status)
# process exited using exit(2) system call; return the
# integer exit(2) system call has been called with
elif os.WIFEXITED(status):
return os.WEXITSTATUS(status)
else:
# should never happen
raise RuntimeError("unknown process exit status")
def get_disk_usage(path):
"""Return disk usage associated with path."""
st = os.statvfs(path)
free = (st.f_bavail * st.f_frsize)
total = (st.f_blocks * st.f_frsize)
used = (st.f_blocks - st.f_bfree) * st.f_frsize
percent = usage_percent(used, total, _round=1)
# NB: the percentage is -5% than what shown by df due to
# reserved blocks that we are currently not considering:
# http://goo.gl/sWGbH
return nt_diskinfo(total, used, free, percent)
def _get_terminal_map():
ret = {}
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
for name in ls:
assert name not in ret
ret[os.stat(name).st_rdev] = name
return ret
This diff is collapsed.
This diff is collapsed.
/*
* $Id: _psutil_common.c 1142 2011-10-05 18:45:49Z g.rodola $
*
* Copyright (c) 2009, Jay Loden, 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.
*
* Routines common to all platforms.
*/
#include <Python.h>
/*
* Set OSError(errno=ESRCH, strerror="No such process") Python exception.
*/
PyObject *
NoSuchProcess(void) {
PyObject *exc;
char *msg = strerror(ESRCH);
exc = PyObject_CallFunction(PyExc_OSError, "(is)", ESRCH, msg);
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
return NULL;
}
/*
* Set OSError(errno=EACCES, strerror="Permission denied") Python exception.
*/
PyObject *
AccessDenied(void) {
PyObject *exc;
char *msg = strerror(EACCES);
exc = PyObject_CallFunction(PyExc_OSError, "(is)", EACCES, msg);
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
return NULL;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
* $Id: process_info.h 1060 2011-07-02 18:05:26Z g.rodola $
*
* Copyright (c) 2009, Jay Loden, 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.
*/
#include <Python.h>
#include <windows.h>
PyObject* get_open_files(long pid, HANDLE processHandle);
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment