Python 创建函数和代码重用

1. cat func.py

#!/usr/bin/python

def func():
print "hello,this is a function" def func2():
for i in range(10):
print "this will show function 10 times"
func() def addtion():
sum=2+1
print "1 + 1 = %s" %sum func2()
addtion()

2. cat pysysinfo.py

#!/usr/bin/env python

import subprocess
def uname_func():
uname="uname"
uname_arg="-a"
print "gathering system info with %s command:\n" % uname
subprocess.call([uname,uname_arg]) def disk_func():
diskspace = "df"
diskspace_arg = "-h"
print "gathering disk info %s command:\n" % diskspace
subprocess.call([diskspace,diskspace_arg]) def main():
uname_func()
disk_func() if __name__=="__main__":
main()

3. cat new_pysysinfo.py

#!/usr/bin/env python
from pysysinfo import disk_func
import subprocess def tmp_space():
tmp_usage="du"
tmp_arg="-h"
path="/tmp"
print "space used in /tmp dir"
subprocess.call([tmp_usage,tmp_arg,path]) def main():
disk_func()
tmp_space() if __name__=="__main__":
main()

注:代码 [if __name__=="__main__":] 的使用,使你可以只调用某脚本中的单一函数。

上一篇:JS将指定的时间戳转为UTC时间


下一篇:iNeuOS工业互联平台,聚合和变化率计算、设备IO和通讯状态、组态快捷键、创建文件夹、选择应用图标等,发布:v3.6版本