python系统管理第1章,python中执行命令,python函数,面向对像编程,通过import语句实现代码复用,,1、Python中执


1、Python中执行命令

例子1:

[root@localhostopt]#catpyls.py#!/usr/bin/envpython#pythonwrapperforthelscommandimportsubprocesssubprocess.call(["ls","-l"])

例子2:

[root@localhostopt]#catpysysinfo.py#!/usr/bin/envpythonimportsubprocess#Command1uname="uname"uname_arg="-a"print"GatheringSysteminformationwith%scommand:\n"%unamesubprocess.call([uname,uname_arg])#Command2diskspace="df"diskspace_arg="-h"print"Gatheringdiskspaceinformationwith%scommand:\n"%diskspacesubprocess.call([diskspace,diskspace_arg])


2、Python函数

[root@localhostopt]#catpysysinfo_func.py#!/usr/bin/envpython#_*_coding:utf-8_*_importsubprocess#Command1defuname_func():#函数体下面要有缩进,缩进要对齐,属于同一个级别uname="uname"uname_arg="-a"print"GatheringSysteminformationwith%scommand:\n"%unamesubprocess.call([uname,uname_arg])#Command2defdisk_func():diskspace="df"diskspace_arg="-h"print"Gatheringdiskspaceinformationwith%scommand:\n"%diskspacesubprocess.call([diskspace,diskspace_arg])defmain():uname_func()#调用函数disk_func()main()#调用主函数


3、面向对像编程

[root@localhostopt]#vimpyServerClass.py#!/usr/bin/envpython#_*_coding:utf-8_*_classServer(object):#class关健字,Server类的名称,断承object类,object类的名称,也就是object是父类def__init__(self,ip,hostname):#定义构造器self.ip=ipself.hostname=hostnamedefset_user(self,user):self.test=userdefping(self,ip_addr):print"Pinging%sfrom%s(%s)useris%s"%(ip_addr,self.ip,self.hostname,self.test)#__name__意思就是如果这个py文件以顶层执行就会等于__main__if__name__==‘__main__‘:#__name__属于模块内置属性,写的一个py文件就属于一个模块,存储他名称server=Server(‘192.168.1.20‘,‘bumbly‘)server.set_user(‘wsyht‘)server.ping(‘192.168.1.15‘)


4、通过import语句实现代码复用

[root@localhostopt]#catpynewsysinfo.py#!/usr/bin/envpythonimportsubprocessfrompysysinfo_funcimportdisk_funcdeftmp_spack():tmp_usage="du"tmp_arg="-h"path="/opt"print"Spaceusedin/optdirectory"subprocess.call([tmp_usage,tmp_arg,path])defmain():disk_functmp_spack()if__name__==‘__main__‘:main()


本文出自 “wsyht的博客” 博客,请务必保留此出处http://wsyht2015.blog.51cto.com/9014030/1794438

python系统管理第1章,python中执行命令,python函数,面向对像编程,通过import语句实现代码复用

评论关闭