Python基础【day01】:初始模块(五)

本节内容

   1、标准库

    1、sys

              2、os

   2、第三方库

    1、for mac

              2、for linux

Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持

1、标准库

python的标准库有很多,我们先认识sys和os模块,因为这两个模块在开发中用的最多

①sys

sys模块操作模块搜索路径、使用sys模块查找内建模块、使用sys模块查找已导入的模块等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __auther__ ==
 
import sys
 
print(sys.argv)#打印的是模块本身的相对路径
 
#输出
$ python test.py helo world
['test.py''helo''world'
#把执行脚本时传递的参数获取到了
 
print(sys.path)#输出Python的执行路径
#输出
['D:\PycharmProjects\pyhomework\day2''D:\PycharmProjects\pyhomework',
'D:\Python\Python35\python35.zip''D:\Python\Python35\DLLs',
'D:\Python\Python35\lib''D:\Python\Python35''D:\Python\Python35\lib\site-packages']
#其中 'D:\Python\Python35\lib\site-packages' 是第三方库安装的路径

 ②os

os,语义为操作系统,所以肯定就是操作系统相关的功能了,可以处理文件和目录这些我们日常手动需要做的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __auther__ ==
 
import os
cmd_reslut = os.system("dir")
print(cmd_reslut)
#输出
#命令被执行,执行完成后会返回一个状态:0表示执行成功,其他数字表示执行失败
cmd_reslut = os.popen("dir").read()
print(cmd_reslut)
#输出
#命令被执行,且执行后的结果返回出来

 ③两个完美结合

1
2
3
4
5
6
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __auther__ ==
 
import sys,os
os.system(''.join(sys.argv[1:]))#把用户的输入的参数当作一条命令交给os.system来执行

 2、第三方库

python tab补全模块

for mac

1 import sys
2 import readline
3 import rlcompleter
4 
5 if sys.platform == 'darwin' and sys.version_info[0] == 2:
6     readline.parse_and_bind("bind ^I rl_complete")
7 else:
8     readline.parse_and_bind("tab: complete")  # linux and python3 on mac

for linux

 1 #!/usr/bin/env python 
 2 # python startup file 
 3 import sys
 4 import readline
 5 import rlcompleter
 6 import atexit
 7 import os
 8 # tab completion 
 9 readline.parse_and_bind('tab: complete')
10 # history file 
11 histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
12 try:
13     readline.read_history_file(histfile)
14 except IOError:
15     pass
16 atexit.register(readline.write_history_file, histfile)
17 del os, histfile, readline, rlcompleter

写完保存后就可以使用了

1
2
3
4
5
localhost:~ jieli$ python
Python 2.7.10 (default, Oct 23 201518: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环境变量列表。

原文地址:https://www.cnblogs.com/luoahong/p/7159812.html