Python模块使用实例展示,清晰明了,不看就亏了

    /    2018-06-22

  Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,以后的课程中会深入讲解常用到的各种库,现在,我们先来象征性的学2个简单的。

  sys

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
print(sys.argv)
#输出
$ python test.py helo world
['test.py', 'helo', 'world'] #把执行脚本时传递的参数获取到了

  os

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.system("df -h") #调用系统命令

  完全结合一下

import os,sys
os.system(''.join(sys.argv[1:])) #把用户的输入的参数当作一条命令交给os.system来执行

  自己写个模块

  Python tab补全模块

import sys
import readline
import rlcompleter
 
if sys.platform == 'darwin' and sys.version_info[0] == 2:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete") # linux and python3 on mac
#!/usr/bin/env python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

  写完保存后就可以使用了

localhost:~ jieli$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tab

  你会发现,上面自己写的tab.py模块只能在当前目录下导入,如果想在系统的何何一个地方都使用怎么办呢? 此时你就要把这个tab.py放到Python全局环境变量目录里啦,基本一般都放在一个叫 Python/2.7/site-packages 目录下,这个目录在不同的OS里放的位置不一样,用 print(sys.path) 可以查看Python环境变量列表。

(2)

分享至