python学习 —— 获取系统运行情况信息并在Linux下设置定时运行python脚本

  代码:

# -*- coding:utf-8 -*-
from psutil import *


def cpu_usage_rate():
    for i, j in zip(range(1, cpu_count(logical=False) + 1), cpu_percent(interval=1, percpu=True)):
        print 'CPU' + str(i) + ':' + str(j) + '%'


def memory_usage_rate():
    vime = virtual_memory()
    print 'Memory: %5s%% %6s/%s' % (
        vime.percent, str(int(vime.used / 1024 / 1024)) + 'M', str(int(vime.total / 1024 / 1024)) + 'M')


def get_disk_info():
    print '磁盘信息:'
    for i in disk_io_counters(perdisk=True).items():
        print i
    # Disk = namedtuple('Disk',
    #                   'major_number minor_number device_name read_count read_merged_count read_sections '
    #                   'time_spent_reading write_count write_merged_count write_sections time_spent_write io_requests '
    #                   'time_spent_doing_io weighted_time_spent_doing_do')
    #
    # with open('/proc/diskstats') as f:
    #     for line in f:
    #         if line.split()[2] == device:
    #             return Disk(*line.split())
    # raise RuntimeError('device ({0}) not found!'.format(device))


def get_net_info():
    print '网络情况:'
    for i in net_io_counters(pernic=True).items():
        print i


def main():
    print '—'*100
    cpu_usage_rate()
    print '
'
    memory_usage_rate()
    print '
'
    get_net_info()
    print '
'
    get_disk_info()
    print '
'


if __name__ == '__main__':
    main()

  2.设置定时运行python脚本

    以我的电脑安装的情况为例,我装的CentOS自带有crontab,所以不需要下载以及安装过程了,而且我的CentOS貌似不太一样,自带的不是shell命令运行环境而是bash,如果不知道自己的是什么可以使用下面命令查看:

which shell

  如果提示没有的话就可能是bash,或者再输入:

which bash

  接下来,直接使用命令:

crontab -e

  打开编辑页面,这里我的并没有配置环境变量,自动默认打开vim,如果需要配置的话,就要找到.profile文件夹,如果是bash,则文件夹名是:.bash_profile,这样名称的文件是隐藏文件,可在文件管理界面使用Ctrl + h看见隐藏文件。然后,在其中添加如下语句即可设置为默认使用vim打开:

EDITOR=vi; export EDITOR

  详见:http://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/crontab.html

  接下来,可以先看看crontab命令的语法格式,使用命令查看

$ cat /etc/crontab

   Output:

  最后一行即是用法。

  最后,要执行python脚本,则编辑内容可如下(需要注意的是貌似需要提前建好.log的日志文件,不然会在var/mail/user中提示找不到文件):

*/1 * * * * python /test.py >> /test.log 2>&1

  对这段语法,这里有更好的解释:https://www.the5fire.com/ubuntu-crontab.html

  最后,我遇到的坑应该是非常少的了,所以,不一定合适解决所有人的问题,如有遇到其他情况,还请自行多查些资料,慢慢解决。

  参考资料:

    1.http://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/crontab.html

    2.https://www.the5fire.com/ubuntu-crontab.html

原文地址:https://www.cnblogs.com/darkchii/p/9015408.html