sys模块
>>> import sys 导入sys模块
>>> sys.version 获取Python的版本信息
'2.7.10 (default, Dec 4 2015, 22:23:19) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)]'
>>> sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
>>> sys.exit() 退出程序,正常退出时exit(0)
>>> sys.argv 命令行参数List,第一个元素是程序本身路径
['']
>>> sys.argv.append('tudou')
>>> sys.argv.append('digua')
>>> sys.argv
['', 'tudou', 'digua']
>>> sys.argv[0]
''
>>> sys.argv[1]
'tudou'
>>> sys.argv[2]
'digua'
>>> len(sys.argv)
3
[root@python ~]# cat hello.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#exec python hello.py Bob
import sys
def hello():
args = sys.argv
if len(args) == 1:
print 'hello world!'
elif len(args) == 2:
print 'hello %s!' % args[1]
else:
print 'Too many arguments!'
if __name__=="__main__":
hello()
[root@python ~]# python hello.py
hello world!
[root@python ~]# python hello.py Bob
hello Bob!
[root@python ~]# python hello.py tudou digua
Too many arguments!
os模块
>>> import os
>>> os.system('touch test.txt') 运行shell命令,创建文件
0
>>> os.system('ls')
anaconda-ks.cfg get-pip.py hello.py install.log install.log.syslog plus.py Python-2.7.10 Python-2.7.10.tgz test.txt
0
>>> os.rename('test.txt','tudou.txt') 重命名文件/目录
>>> os.system('ls')
anaconda-ks.cfg get-pip.py hello.py install.log install.log.syslog plus.py Python-2.7.10 Python-2.7.10.tgz tudou.txt
0
>>> os.remove('tudou.txt') 删除文件
>>> os.system('ls')
anaconda-ks.cfg get-pip.py hello.py install.log install.log.syslog plus.py Python-2.7.10 Python-2.7.10.tgz
0
>>> os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
'/root'
>>> os.chdir('/usr/local') 改变当前脚本工作目录;相当于shell下cd
>>> os.getcwd() 显示当前所在目录
'/usr/local'