练习1、调用subprocess模块,执行df命令,查看磁盘使用情况
vim pydf.py
#!/usr/bin/env python
#python wrapper for the ls command
import subprocess
subprocess.call(["df","-h"])
[root@sio python]# python pydf.py
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 40G 11G 27G 29% /
tmpfs 32G 0 32G 0% /dev/shm
/dev/mapper/a8data-a8data01
483G 17G 442G 4% /a8root
练习2、调用subprocess模块,执行ls命令,查看文件列表
vim pyls.py
#!/usr/bin/env python
#python wrapper for the ls command
import subprocess
subprocess.call(["ls","-l"])
练习3、调用subprocess模块,执行df uname命令,查看信息
vim pyinfo.py
#!/usr/bin/env python
#python wrapper for the ls command
import subprocess
#Command1
uname="uname"
uname_arg="-a"
print "\033[1;32;40mGathering System information with %s command:\033[0m\n" % uname
subprocess.call([uname,uname_arg])
#Command2
df="df"
df_arg="-h"
print "\033[1;32;40mGathering diskspace information with %s command:\033[0m\n" % df
subprocess.call([df,df_arg])
练习4、将其写成函数形式
vim pyinfo_func.py
#!/usr/bin/env python
#python wrapper for the ls command
import subprocess
#Command1
def uname_func():
uname="uname"
uname_arg="-a"
print "\033[1;32;40mGathering System information with %s command:\033[0m\n" % uname
subprocess.call([uname,uname_arg])
#Command2
def disk_func():
df="df"
df_arg="-h"
print "\033[1;32;40mGathering diskspace information with %s command:\033[0m\n" % df
subprocess.call([df,df_arg])
def main():
uname_func()
disk_func()
main()
练习5、简化函数
vim pyinfo_func_2.py
#!/usr/bin/env python
#python wrapper for the ls command
import subprocess
def command_func(cmd,cmd_arg):
print "\033[1;32;40mGathering System information with %s command:\033[0m\n" % cmd
subprocess.call([cmd,cmd_arg])
def main():
command_func("uname","-a")
command_func("df","-h")
if __name__=='__main__':
main()
练习6、调用自己写的函数
vim py_new.py
#!/usr/bin/env python
import subprocess
from pyinfo_func_2 import command_func
def main():
command_func('df','-h')
if __name__=='__main__':
main()