标签归档:freebsd

如何离线安装软件包?

问题:如何离线安装软件包?

从pypi下载python软件包的最佳方法是什么,以便从另一台计算机上脱机安装?有什么简单的方法可以通过pip或easy_install来做到这一点?我正在尝试在未连接到Internet的FreeBSD盒上安装请求库。

What’s the best way to download a python package and it’s dependencies from pypi for offline installation on another machine? Is there any easy way to do this with pip or easy_install? I’m trying to install the requests library on a FreeBSD box that is not connected to the internet.


回答 0

如果该软件包位于PYPI上,则将其及其依赖项下载到某个本地目录。例如

$ mkdir / pypi && cd / pypi
$ ls -la
  -rw-r--r-- 1个Pavel人员237954 Apr 19 11:31 Flask-WTF-0.6.tar.gz
  -rw-r--r-- 1个Pavel员工389741 2月22日17:10 Jinja2-2.6.tar.gz
  -rw-r--r-- 1个Pavel人员70305 Apr 11 00:28 MySQL-python-1.2.3.tar.gz
  -rw-r--r-- 1个Pavel人员2597214 Apr 10 18:26 SQLAlchemy-0.7.6.tar.gz
  -rw-r--r-- 1个Pavel员工1108056 2月22日17:10 Werkzeug-0.8.2.tar.gz
  -rw-r--r-- 1个Pavel员工488207 Apr 10 18:26 boto-2.3.0.tar.gz
  -rw-r--r-- 1个Pavel人员490192 4月16日12:00 flask-0.9-dev-2a6c80a.tar.gz

某些软件包可能必须手工存档到外观相似的tarball中。当我想要某个东西的最新版本(不稳定)时,我会做很多事情。某些软件包不在PYPI上,因此也适用于它们。

假设您在中有一个格式正确的Python应用程序~/src/myapp~/src/myapp/setup.py将会install_requires列出您/pypi目录中的一或多个内容的列表。像这样:

  install_requires=[
    'boto',
    'Flask',
    'Werkzeug',
    # and so on

如果您希望能够在拥有所有必要依赖项的情况下运行您的应用程序,同时仍然对其进行黑客攻击,则可以执行以下操作:

$ cd〜/ src / myapp
$ python setup.py开发--always-unzip --allow-hosts = None --find-links = / pypi

这样,您的应用将直接从您的源目录执行。您可以破解某些东西,然后重新运行该应用程序而无需重建任何内容。

如果要将应用程序及其依赖项安装到当前的python环境中,请执行以下操作:

$ cd〜/ src / myapp
$ easy_install --always-unzip --allow-hosts = None --find-links = / pypi。

在这两种情况下,如果/pypi目录中不存在一个或多个依赖项,构建都将失败。它不会尝试从Internet混杂地安装丢失的东西。

我强烈建议在活动的虚拟环境中调用它setup.py develop ...,以避免污染全局Python环境。(virtualenv是)几乎可以走的路。切勿在全局Python环境中安装任何东西。easy_install ...

如果您构建了应用程序的计算机与要在其上部署应用程序的计算机具有相同的体系结构,则可以将所有easy_install内容都放入其中的整个虚拟环境目录中。不过,在压缩之前,您必须使虚拟环境目录可重定位(请参见 –relocatable选项)。注意:目标计算机需要安装相同版本的Python,并且应用程序可能也已经预安装了基于C的任何依赖关系(例如,如果您依赖PIL,那么必须预安装libpng,libjpeg等) 。

If the package is on PYPI, download it and its dependencies to some local directory. E.g.

$ mkdir /pypi && cd /pypi
$ ls -la
  -rw-r--r--   1 pavel  staff   237954 Apr 19 11:31 Flask-WTF-0.6.tar.gz
  -rw-r--r--   1 pavel  staff   389741 Feb 22 17:10 Jinja2-2.6.tar.gz
  -rw-r--r--   1 pavel  staff    70305 Apr 11 00:28 MySQL-python-1.2.3.tar.gz
  -rw-r--r--   1 pavel  staff  2597214 Apr 10 18:26 SQLAlchemy-0.7.6.tar.gz
  -rw-r--r--   1 pavel  staff  1108056 Feb 22 17:10 Werkzeug-0.8.2.tar.gz
  -rw-r--r--   1 pavel  staff   488207 Apr 10 18:26 boto-2.3.0.tar.gz
  -rw-r--r--   1 pavel  staff   490192 Apr 16 12:00 flask-0.9-dev-2a6c80a.tar.gz

Some packages may have to be archived into similar looking tarballs by hand. I do it a lot when I want a more recent (less stable) version of something. Some packages aren’t on PYPI, so same applies to them.

Suppose you have a properly formed Python application in ~/src/myapp. ~/src/myapp/setup.py will have install_requires list that mentions one or more things that you have in your /pypi directory. Like so:

  install_requires=[
    'boto',
    'Flask',
    'Werkzeug',
    # and so on

If you want to be able to run your app with all the necessary dependencies while still hacking on it, you’ll do something like this:

$ cd ~/src/myapp
$ python setup.py develop --always-unzip --allow-hosts=None --find-links=/pypi

This way your app will be executed straight from your source directory. You can hack on things, and then rerun the app without rebuilding anything.

If you want to install your app and its dependencies into the current python environment, you’ll do something like this:

$ cd ~/src/myapp
$ easy_install --always-unzip --allow-hosts=None --find-links=/pypi .

In both cases, the build will fail if one or more dependencies aren’t present in /pypi directory. It won’t attempt to promiscuously install missing things from Internet.

I highly recommend to invoke setup.py develop ... and easy_install ... within an active virtual environment to avoid contaminating your global Python environment. It is (virtualenv that is) pretty much the way to go. Never install anything into global Python environment.

If the machine that you’ve built your app has same architecture as the machine on which you want to deploy it, you can simply tarball the entire virtual environment directory into which you easy_install-ed everything. Just before tarballing though, you must make the virtual environment directory relocatable (see –relocatable option). NOTE: the destination machine needs to have the same version of Python installed, and also any C-based dependencies your app may have must be preinstalled there too (e.g. say if you depend on PIL, then libpng, libjpeg, etc must be preinstalled).


回答 1

pip download命令使您无需安装即可下载软件包:

pip download -r requirements.txt

(在以前的pip版本中,拼写为 pip install --download -r requirements.txt。)

然后,您可以使用它们pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt来安装那些下载的sdist,而无需访问网络。

The pip download command lets you download packages without installing them:

pip download -r requirements.txt

(In previous versions of pip, this was spelled pip install --download -r requirements.txt.)

Then you can use pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt to install those downloaded sdists, without accessing the network.


回答 2

如果要脱机安装python库及其依赖项,请在具有相同操作系统,网络连接和python安装的机器上完成以下步骤:

1)创建一个requirements.txt内容相似的文件(注意-这些是您要下载的库):

Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0

创建需求文件的一种方法是使用pip freeze > requirements.txt。这将列出您环境中的所有库。那你可以进去requirements.txt并删除不需要的对象。

2)执行命令 mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse以将库及其依赖项下载到目录wheelhouse

3)将requirements.txt复制到 wheelhouse目录中

4)存档驾驶室成wheelhouse.tar.gztar -zcf wheelhouse.tar.gz wheelhouse

然后上传wheelhouse.tar.gz到目标计算机:

1)执行tar -zxf wheelhouse.tar.gz以提取文件

2)执行pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse以安装库及其依赖项

If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:

1) Create a requirements.txt file with similar content (Note – these are the libraries you wish to download):

Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0

One option for creating the requirements file is to use pip freeze > requirements.txt. This will list all libraries in your environment. Then you can go in to requirements.txt and remove un-needed ones.

2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse to download libs and their dependencies to directory wheelhouse

3) Copy requirements.txt into wheelhouse directory

4) Archive wheelhouse into wheelhouse.tar.gz with tar -zcf wheelhouse.tar.gz wheelhouse

Then upload wheelhouse.tar.gz to your target machine:

1) Execute tar -zxf wheelhouse.tar.gz to extract the files

2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse to install the libs and their dependencies


回答 3

离线python。为此,我使用virtualenv(隔离的Python环境)

1)使用pip在线安装virtualenv:

pip install virtualenv --user

或使用whl脱机:转到此链接,下载最新版本(.whl或tar.gz),然后使用以下命令进行安装:

pip install virtualenv-15.1.0-py2.py3-none-any.whl --user

通过使用--user您不需要使用sudo pip…

2)使用virtualenv

在联机计算机上,选择带有终端的目录cd并运行以下代码:

python -m virtualenv myenv
cd myenv
source bin/activate
pip install Flask

安装所有软件包后,必须requirements.txt在virtualenv处于活动状态时生成一个,以便

pip freeze > requirements.txt

打开一个新终端并创建另一个env之类的myenv2

python -m virtualenv myenv2
cd myenv2
source bin/activate
cd -
ls

现在,您可以转到您的requirements.txttranferred_packages文件夹所在的脱机文件夹。使用以下代码下载软件包,并将其全部放入tranferred_packages文件夹。

pip download -r requirements.txt

将您的脱机文件夹移至脱机计算机,然后

python -m virtualenv myenv2
cd myenv2
source bin/activate
cd -
cd offline
pip install --no-index --find-links="./tranferred_packages" -r requirements.txt

离线文件夹中的内容[requirements.txt,tranferred_pa​​ckages {Flask-0.10.1.tar.gz,…}]

检查包裹清单

pip list

注意:与2017年一样,最好使用python3。您可以使用此命令创建python 3 virtualenv。

virtualenv -p python3 envname

offline python. for doing this I use virtualenv (isolated Python environment)

1) install virtualenv online with pip:

pip install virtualenv --user

or offline with whl: go to this link , download last version (.whl or tar.gz) and install that with this command:

pip install virtualenv-15.1.0-py2.py3-none-any.whl --user

by using --user you don’t need to use sudo pip….

2) use virtualenv

on online machine select a directory with terminal cd and run this code:

python -m virtualenv myenv
cd myenv
source bin/activate
pip install Flask

after installing all the packages, you have to generate a requirements.txt so while your virtualenv is active, write

pip freeze > requirements.txt

open a new terminal and create another env like myenv2.

python -m virtualenv myenv2
cd myenv2
source bin/activate
cd -
ls

now you can go to your offline folder where your requirements.txt and tranferred_packages folder are in there. download the packages with following code and put all of them to tranferred_packages folder.

pip download -r requirements.txt

take your offline folder to offline computer and then

python -m virtualenv myenv2
cd myenv2
source bin/activate
cd -
cd offline
pip install --no-index --find-links="./tranferred_packages" -r requirements.txt

what is in the folder offline [requirements.txt , tranferred_packages {Flask-0.10.1.tar.gz, …}]

check list of your package

pip list

note: as we are in 2017 it is better to use python 3. you can create python 3 virtualenv with this command.

virtualenv -p python3 envname

回答 4

下载压缩包,将其转移到您的FreeBSD机器上并解压缩,然后运行python setup.py install就可以了!

编辑:只是要补充一点,您现在也可以使用pip安装tarball。

Download the tarball, transfer it to your FreeBSD machine and extract it, afterwards run python setup.py install and you’re done!

EDIT: Just to add on that, you can also install the tarballs with pip now.


回答 5

让我一步一步地完成该过程:

  1. 在连接到互联网的计算机上,创建一个文件夹。
   $ mkdir packages
   $ cd packages
  1. 打开命令提示符或shell并执行以下命令:

    假设您想要的软件包是 tensorflow

    $ pip download tensorflow

  2. 现在,在目标计算机上,复制packages文件夹并应用以下命令

  $ cd packages
  $ pip install 'tensorflow-xyz.whl' --no-index --find-links '.'

请注意,tensorflow-xyz.whl必须将替换为所需软件包的原始名称。

Let me go through the process step by step:

  1. On a computer connected to the internet, create a folder.
   $ mkdir packages
   $ cd packages
  1. open up a command prompt or shell and execute the following command:

    Suppose the package you want is tensorflow

    $ pip download tensorflow

  2. Now, on the target computer, copy the packages folder and apply the following command

  $ cd packages
  $ pip install 'tensorflow-xyz.whl' --no-index --find-links '.'

Note that the tensorflow-xyz.whl must be replaced by the original name of the required package.


回答 6

使用wheel编译包。

打包:

$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)
$ pip wheel -r requirements.txt --wheel-dir=$tempdir
$ cwd=`pwd`
$ (cd "$tempdir"; tar -cjvf "$cwd/bundled.tar.bz2" *)

复制tarball并安装:

$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)
$ (cd $tempdir; tar -xvf /path/to/bundled.tar.bz2)
$ pip install --force-reinstall --ignore-installed --upgrade --no-index --no-deps $tempdir/*

注意wheel二进制软件包不是跨机器的。

更多参考 此处:https : //pip.pypa.io/en/stable/user_guide/#installation-bundles

Using wheel compiled packages.

bundle up:

$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)
$ pip wheel -r requirements.txt --wheel-dir=$tempdir
$ cwd=`pwd`
$ (cd "$tempdir"; tar -cjvf "$cwd/bundled.tar.bz2" *)

copy tarball and install:

$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)
$ (cd $tempdir; tar -xvf /path/to/bundled.tar.bz2)
$ pip install --force-reinstall --ignore-installed --upgrade --no-index --no-deps $tempdir/*

Note wheel binary packages are not across machines.

More ref. here: https://pip.pypa.io/en/stable/user_guide/#installation-bundles


回答 7

我有一个类似的问题。而且我必须以相同的方式安装它,我们是从pypi安装的。

我做了以下事情:

  1. 创建一个目录以存储机器中所有可以访问Internet的软件包。

    mkdir -p /path/to/packages/
  2. 将所有软件包下载到路径

    pip download -r requirements.txt -d /path/to/packages
    
    Eg:- ls /root/wheelhouse/  # **/root/wheelhouse** is my **/path/to/packages/**
    total 4524
    -rw-r--r--. 1 root root   16667 May 23  2017 incremental-17.5.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   34713 Sep  1 10:21 attrs-18.2.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root 3088398 Oct 15 14:41 Twisted-18.9.0.tar.bz2
    -rw-r--r--. 1 root root  133356 Jan 28 15:58 chardet-3.0.4-py2.py3-none-any.whl
    -rw-r--r--. 1 root root  154154 Jan 28 15:58 certifi-2018.11.29-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   57987 Jan 28 15:58 requests-2.21.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   58594 Jan 28 15:58 idna-2.8-py2.py3-none-any.whl
    -rw-r--r--. 1 root root  118086 Jan 28 15:59 urllib3-1.24.1-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   47229 Jan 28 15:59 tqdm-4.30.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root    7922 Jan 28 16:13 constantly-15.1.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root  164706 Jan 28 16:14 zope.interface-4.6.0-cp27-cp27mu-manylinux1_x86_64.whl
    -rw-r--r--. 1 root root  573841 Jan 28 16:14 setuptools-40.7.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   37638 Jan 28 16:15 Automat-0.7.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   37905 Jan 28 16:15 hyperlink-18.0.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   52311 Jan 28 16:15 PyHamcrest-1.9.0-py2.py3-none-any.whl
    -rw-r--r--. 1 root root   10586 Jan 28 16:15 six-1.12.0-py2.py3-none-any.whl
  3. 压缩软件包目录,然后将其复制到没有Internet访问权限的计算机上。然后做,

    cd /path/to/packages/
    tar -cvzf packages.tar.gz .  # not the . (dot) at the end

    packages.tar.gz复制到没有Internet访问权限的目标计算机中。

  4. 在无法访问互联网的计算机上,执行以下操作(假设您将已解压缩的软件包复制到当前计算机上的/ path / to / package /中)

    cd /path/to/packages/
    tar -xvzf packages.tar.gz
    mkdir -p $HOME/.config/pip/
    
    vi $HOME/.config/pip/pip.conf

    并将以下内容粘贴并保存。

    [global]
    timeout = 10
    find-links = file:///path/to/package/
    no-cache-dir = true
    no-index = true
  5. 最后,我建议您使用某种形式的virtualenv安装软件包。

    virtualenv -p python2 venv # use python3, if you are on python3
    source ./venv/bin/activate
    pip install <package>

您应该能够下载目录/ path / to / package /中的所有模块。

注意:我只是这样做,因为我无法添加选项或更改我们安装模块的方式。不然我会做的

    pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt

I had a similar problem. And i had to make it install the same way, we do from pypi.

I did the following things:

  1. Make a directory to store all the packages in the machine that have internet access.

    mkdir -p /path/to/packages/
    
  2. Download all the packages to the path

Edit: You can also try:

python3 -m pip wheel --no-cache-dir -r requirements.txt -w /path/to/packages
pip download -r requirements.txt -d /path/to/packages

Eg:- ls /root/wheelhouse/  # **/root/wheelhouse** is my **/path/to/packages/**
total 4524
-rw-r--r--. 1 root root   16667 May 23  2017 incremental-17.5.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root   34713 Sep  1 10:21 attrs-18.2.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 3088398 Oct 15 14:41 Twisted-18.9.0.tar.bz2
-rw-r--r--. 1 root root  133356 Jan 28 15:58 chardet-3.0.4-py2.py3-none-any.whl
-rw-r--r--. 1 root root  154154 Jan 28 15:58 certifi-2018.11.29-py2.py3-none-any.whl
-rw-r--r--. 1 root root   57987 Jan 28 15:58 requests-2.21.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root   58594 Jan 28 15:58 idna-2.8-py2.py3-none-any.whl
-rw-r--r--. 1 root root  118086 Jan 28 15:59 urllib3-1.24.1-py2.py3-none-any.whl
-rw-r--r--. 1 root root   47229 Jan 28 15:59 tqdm-4.30.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root    7922 Jan 28 16:13 constantly-15.1.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root  164706 Jan 28 16:14 zope.interface-4.6.0-cp27-cp27mu-manylinux1_x86_64.whl
-rw-r--r--. 1 root root  573841 Jan 28 16:14 setuptools-40.7.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root   37638 Jan 28 16:15 Automat-0.7.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root   37905 Jan 28 16:15 hyperlink-18.0.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root   52311 Jan 28 16:15 PyHamcrest-1.9.0-py2.py3-none-any.whl
 -rw-r--r--. 1 root root   10586 Jan 28 16:15 six-1.12.0-py2.py3-none-any.whl
  1. Tar the packages directory and copy it to the Machine that doesn’t have internet access. Then do,

    cd /path/to/packages/
    tar -cvzf packages.tar.gz .  # not the . (dot) at the end
    

Copy the packages.tar.gz into the destination machine that doesn’t have internet access.

  1. In the machine that doesn’t have internet access, do the following (Assuming you copied the tarred packages to /path/to/package/ in the current machine)

    cd /path/to/packages/
    tar -xvzf packages.tar.gz
    mkdir -p $HOME/.config/pip/
    vi $HOME/.config/pip/pip.conf
    

and paste the following content inside and save it.

[global]
timeout = 10
find-links = file:///path/to/package/
no-cache-dir = true
no-index = true
  1. Finally, i suggest you use, some form of virtualenv for installing the packages.

    virtualenv -p python2 venv # use python3, if you are on python3
    source ./venv/bin/activate
    pip install <package>
    

You should be able to download all the modules that are in the directory /path/to/package/.

Note: I only did this, because i couldn’t add options or change the way we install the modules. Otherwise i’d have done

pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt

回答 8

对于Pip 8.1.2,您可以用于pip download -r requ.txt将软件包下载到本地计算机。

For Pip 8.1.2 you can use pip download -r requ.txt to download packages to your local machine.


Psutil-Python中用于进程和系统监控的跨平台库

摘要

psutil(进程和系统实用程序)是一个跨平台库,用于检索正在运行的进程系统利用率(CPU、内存、磁盘、网络、传感器)。它主要用于系统监控分析和限制进程资源正在运行的进程的管理它实现了经典UNIX命令行工具提供的许多功能,例如ps、top、iotop、lsof、netstat、ifconfig、free还有其他人。psutil目前支持以下平台:

  • Linux操作系统
  • 窗口
  • MacOS
  • FreeBSD、OpenBSDNetBSD
  • Sun Solaris
  • AIX

支持的Python版本包括2.62.73.4+PyPy

资金来源

虽然psutil是自由软件,并且将永远是自由软件,但该项目将从一些资金中获益良多。就时间而言,只对我一个人来说,跟上错误报告和维护已经变得很难持续了。如果您是一家大量使用psutil的公司,您可以考虑通过以下方式成为赞助商GitHub SponsorsOpen CollectivePayPal并将您的徽标显示在此处和标牌上doc

赞助商

add your logo

支持者




add your avatar

贡献

看见contributing guidelines

用法示例

这几乎代表了整个psutil api。

CPU

>>> import psutil
>>>
>>> psutil.cpu_times()
scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)
>>>
>>> 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, 3.7, 9.2]
[7.0, 8.5, 2.4, 2.1]
[1.2, 9.0, 9.9, 7.2]
>>>
>>> for x in range(3):
...     psutil.cpu_times_percent(interval=1, percpu=False)
...
scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
>>>
>>> psutil.cpu_count()
4
>>> psutil.cpu_count(logical=False)
2
>>>
>>> psutil.cpu_stats()
scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
>>>
>>> psutil.cpu_freq()
scpufreq(current=931.42925, min=800.0, max=3500.0)
>>>
>>> psutil.getloadavg()  # also on Windows (emulated)
(3.14, 3.89, 4.67)

内存

>>> psutil.virtual_memory()
svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
>>> psutil.swap_memory()
sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)
>>>

磁盘

>>> psutil.disk_partitions()
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid', maxfile=255, maxpath=4096),
 sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw', maxfile=255, maxpath=4096)]
>>>
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
>>>
>>> psutil.disk_io_counters(perdisk=False)
sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412)
>>>

网络

>>> psutil.net_io_counters(pernic=True)
{'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
>>>
>>> psutil.net_connections(kind='tcp')
[sconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),
 sconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987),
 ...]
>>>
>>> psutil.net_if_addrs()
{'lo': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
        snicaddr(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
        snicaddr(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
 'wlan0': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
           snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
           snicaddr(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
>>>
>>> psutil.net_if_stats()
{'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536),
 'wlan0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500)}
>>>

传感器

>>> import psutil
>>> psutil.sensors_temperatures()
{'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
 'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
 'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
              shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0)]}
>>>
>>> psutil.sensors_fans()
{'asus': [sfan(label='cpu_fan', current=3200)]}
>>>
>>> psutil.sensors_battery()
sbattery(percent=93, secsleft=16628, power_plugged=False)
>>>

其他系统信息

>>> import psutil
>>> psutil.users()
[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),
 suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
>>>
>>> psutil.boot_time()
1365519115.0
>>>

流程管理

>>> import psutil
>>> psutil.pids()
[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
psutil.Process(pid=7055, name='python3', status='running', started='09:04:44')
>>> p.name()
'python3'
>>> p.exe()
'/usr/bin/python3'
>>> p.cwd()
'/home/giampaolo'
>>> p.cmdline()
['/usr/bin/python', 'main.py']
>>>
>>> p.pid
7055
>>> p.ppid()
7054
>>> p.children(recursive=True)
[psutil.Process(pid=29835, name='python3', status='sleeping', started='11:45:38'),
 psutil.Process(pid=29836, name='python3', status='waking', started='11:43:39')]
>>>
>>> p.parent()
psutil.Process(pid=4699, name='bash', status='sleeping', started='09:06:44')
>>> p.parents()
[psutil.Process(pid=4699, name='bash', started='09:06:44'),
 psutil.Process(pid=4689, name='gnome-terminal-server', status='sleeping', started='0:06:44'),
 psutil.Process(pid=1, name='systemd', status='sleeping', started='05:56:55')]
>>>
>>> p.status()
'running'
>>> p.username()
'giampaolo'
>>> p.create_time()
1267551141.5019531
>>> p.terminal()
'/dev/pts/0'
>>>
>>> p.uids()
puids(real=1000, effective=1000, saved=1000)
>>> p.gids()
pgids(real=1000, effective=1000, saved=1000)
>>>
>>> p.cpu_times()
pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1, iowait=0.0)
>>> p.cpu_percent(interval=1.0)
12.1
>>> p.cpu_affinity()
[0, 1, 2, 3]
>>> p.cpu_affinity([0, 1])  # set
>>> p.cpu_num()
1
>>>
>>> p.memory_info()
pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0)
>>> p.memory_full_info()  # "real" USS memory usage (Linux, macOS, Win only)
pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0)
>>> p.memory_percent()
0.7823
>>> p.memory_maps()
[pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0),
 pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0),
 pmmap_grouped(path='[heap]',  rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0),
 pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0),
 ...]
>>>
>>> p.io_counters()
pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543)
>>>
>>> p.open_files()
[popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768),
 popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
>>>
>>> p.connections(kind='tcp')
[pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'),
 pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING')]
>>>
>>> p.num_threads()
4
>>> p.num_fds()
8
>>> p.threads()
[pthread(id=5234, user_time=22.5, system_time=9.2891),
 pthread(id=5237, user_time=0.0707, system_time=1.1)]
>>>
>>> p.num_ctx_switches()
pctxsw(voluntary=78, involuntary=19)
>>>
>>> p.nice()
0
>>> p.nice(10)  # set
>>>
>>> p.ionice(psutil.IOPRIO_CLASS_IDLE)  # IO priority (Win and Linux only)
>>> p.ionice()
pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
>>>
>>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5))  # set resource limits (Linux only)
>>> p.rlimit(psutil.RLIMIT_NOFILE)
(5, 5)
>>>
>>> p.environ()
{'LC_PAPER': 'it_IT.UTF-8', 'SHELL': '/bin/bash', 'GREP_OPTIONS': '--color=auto',
'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
 ...}
>>>
>>> p.as_dict()
{'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...}
>>> p.is_running()
True
>>> p.suspend()
>>> p.resume()
>>>
>>> p.terminate()
>>> p.kill()
>>> p.wait(timeout=3)
<Exitcode.EX_OK: 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
...
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
>>>

进一步的流程API

>>> import psutil
>>> for proc in psutil.process_iter(['pid', 'name']):
...     print(proc.info)
...
{'pid': 1, 'name': 'systemd'}
{'pid': 2, 'name': 'kthreadd'}
{'pid': 3, 'name': 'ksoftirqd/0'}
...
>>>
>>> psutil.pid_exists(3)
True
>>>
>>> def on_terminate(proc):
...     print("process {} terminated".format(proc))
...
>>> # waits for multiple processes to terminate
>>> gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
>>>

Windows服务

>>> list(psutil.win_service_iter())
[<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
 <WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
 <WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
 <WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
 ...]
>>> s = psutil.win_service_get('alg')
>>> s.as_dict()
{'binpath': 'C:\\Windows\\System32\\alg.exe',
 'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
 'display_name': 'Application Layer Gateway Service',
 'name': 'alg',
 'pid': None,
 'start_type': 'manual',
 'status': 'stopped',
 'username': 'NT AUTHORITY\\LocalService'}

使用psutil的项目

这里有一些我觉得特别有趣的:

港口