1、Python中执行命令
例子1:
[[email protected] opt]# cat pyls.py #!/usr/bin/env python #python wrapper for the ls command import subprocess subprocess.call(["ls","-l"])
例子2:
[[email protected] opt]# cat pysysinfo.py #!/usr/bin/env python import subprocess #Command 1 uname="uname" uname_arg="-a" print "Gathering System information with %s command:\n" % uname subprocess.call([uname,uname_arg]) #Command 2 diskspace="df" diskspace_arg="-h" print "Gathering diskspace information with %s command:\n" % diskspace subprocess.call([diskspace,diskspace_arg])
2、Python函数
[[email protected] opt]# cat pysysinfo_func.py #!/usr/bin/env python #_*_ coding:utf-8 _*_ import subprocess #Command 1 def uname_func(): #函数体下面要有缩进,缩进要对齐,属于同一个级别 uname="uname" uname_arg="-a" print "Gathering System information with %s command:\n" % uname subprocess.call([uname,uname_arg]) #Command 2 def disk_func(): diskspace="df" diskspace_arg="-h" print "Gathering diskspace information with %s command:\n" % diskspace subprocess.call([diskspace,diskspace_arg]) def main(): uname_func() #调用函数 disk_func() main() #调用主函数
3、面向对像编程
[[email protected] opt]# vim pyServerClass.py #!/usr/bin/env python #_*_ coding:utf-8 _*_ class Server(object): #class关健字,Server类的名称,断承object类,object类的名称,也就是object是父类 def __init__(self,ip,hostname): #定义构造器 self.ip=ip self.hostname=hostname def set_user(self,user): self.test=user def ping(self,ip_addr): print "Pinging %s from %s (%s) user is %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语句实现代码复用
[[email protected] opt]# cat pynewsysinfo.py #!/usr/bin/env python import subprocess from pysysinfo_func import disk_func def tmp_spack(): tmp_usage="du" tmp_arg="-h" path="/opt" print "Space used in /opt directory" subprocess.call([tmp_usage,tmp_arg,path]) def main(): disk_func tmp_spack() if __name__==‘__main__‘: main()
时间: 2024-10-15 23:58:59