学习Python线程类,在同事指导下写的Linux同步监控程序,代码框架

#程序功能,实现同步监控。由于Linux_shell为单线程的脚本语言。若如要使用几个命令在同一时间开始监控,我们只能开启N个窗口。好在,当初使用shell_script仅仅是用来对内部服务器进行监测。曾经也处理过以下问题,但当时没能找到好的解决办法,只好就此作罢。而这次维护,原本是想在外网某台服务器上部署以上脚本,但苦于同步问题,上周一直研究这方面的内容。Python接触的时间不算太长,这段程序是在没有看完class部分撰写的,相信应该有更为简介的办法可供使用,希望各位Python达人,提出您的宝贵建议,嘿嘿!

#关于此程序的说明:在实现该程序前,初步核对了一下我的需求:

  1. 确保程序记录的数据时间是同步的,不能出现数据错乱的情况
  2. 熟悉threading.Thread的用法,了解self与this共通性,是否存在super的用户,调用基类的构造方法(java的后遗症)
  3. 理解多线程的意义,单线程分割时间处理多个任务
  4. 理解main的用法(哈哈,没想到python这么神奇,连Class都能调,小看了
  5. self、self.name、object.self.name,对象调用基类的变量,这个貌似很难理解,大致没看明白
# !/usr/bin/envpython
#
-*-coding:cp936-*-
import threading,os,time

class Cpuinfo_th(threading.Thread):

def __init__ (self):
threading.Thread.
__init__ (self)
def run(self):
# foriinrange(2):
os.system( " echocpuinfotest " )

class Memoryinfo_th(threading.Thread):

def __init__ (self):
threading.Thread.
__init__ (self)
def run(self):
# foriinrange(2):
os.system( " echomemoryinfotest " )

class Control(Cpuinfo_th,Memoryinfo_th):

def console(self):
# applicationobject
cpuinfo_th = Cpuinfo_th()
memoryinfo_th
= Memoryinfo_th()
# loop
for i in range( 2 ):
time.sleep(
1 )
print " ExecuteOK!,runcpuinfo "
cpuinfo_th.run()
time.sleep(
0.01 )
print " ExecuteOK!,runmemoryinfo "
memoryinfo_th.run()
time.sleep(
0.01 )

class WriteMethod:

def writemethod(data):
path
= " d:\output "
write_list
= open(path, ' w ' )
write_list.write(data)
write_list.close()

if __name__ == " __main__ " :

control
= Control()
control.console()

下面,讲讲我写这个脚本的一些感受:

  • 声明一个类程序,注意两点:首先,类名的头一个字母需要大写;第二,继承是直接写在括号内的,如:(threading.thread);另外,python支持多重继承,好像java是不行的,两个父亲的问题(不过关于基类中,名字相同的方法python是如何处理的,这一点还没有验证过)
class Cpuinfo_th(threading.Thread):
  • 调用系统的command命令(for windows/linux/mac.........)
os.system( " echomemoryinfotest " )
  • 线程时间控制循环及sleep的用法。首先,我们使用Range来控制循环次数,使用第一个sleep()来控制主线程的循环时间,另外连个线程用来控制子线程调度关系,如代码所示:
for i in range( 2 ):
time.sleep(
1 )
print " ExecuteOK!,runcpuinfo "
cpuinfo_th.run()
time.sleep(
0.01 )
print " ExecuteOK!,runmemoryinfo "
memoryinfo_th.run()
time.sleep(
0.01 )
  • 类的对象申明和使用。对象申明可以是用如,object_instance = Classname() 或者直接使用Classname(),以下为了区别方法和类,还是使用java的写法(虽然不太像 Date date = new Date())
if __name__ == " __main__ " :

control
= Control()
control.console()

你可能感兴趣的:(多线程,框架,linux,python,OS)