[Python]浅谈模块(一)

283 阅读6分钟

写在前面的话

  • 有些SK的时候讲过

1. 什么是模块

在Python中一个.py文件就是一个模块。
在Python中有标准库和第三方库之分。

1.1 标准库

安装了Python后默认就安装了很多的库。据传标准库会面临一次大清洗。 位置在主目录的Lib目录下。

image.png

在这个目录下有文件夹。典型的有:

  • logging
  • sqlite3
  • tkinter
  • unittest

在这些目录下有个共同点:都有一个文件叫__init__.py。


也有很多py文件,如:

  • copy.py
  • this.py
  • csv.py
  • io.py

1.2 第三方库

官方网址:pypi.org/,不完全统计有20多万个?

  • 数据分析:numpy,pandas、matplotlib(不知道放这里是否合适)、Tensorflow
  • web框架:flask,django
  • 爬虫相关:Scrapy、requests、BeautifulSoup、spider
  • 图形相关:pillow
  • 数据库:sqlite3、pymysql、pyoracle、cx-oracle等
  • 软件测试:selenium、pytest、unittest

2. 为什么要用模块

模块类似于函数,写代码一方面可以说就是为了解决重复做的问题。
而且好的程序如果分享(开源),大家就可以共享智慧,体现硅步效应,金字塔就这么来了。
可以说一些流行语言之所以流行,优质的模块(库)是其必备的一个条件。

3. 怎么用模块

3.1 导入模块

如果已经安装好了,比如标准库,我们直接导入即可。

  • 语法1
import 模块名

如果要使用模块里面的东西需要用模块.属性的格式,这里的属性可以是很多东西,比如方法,常量等,看下面的例子

>>> import math
>>> math.pi
3.141592653589793
>>> pi   #直接调用报错
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    pi
NameError: name 'pi' is not defined

如果我们每次调用都要加上模块名,还是有点麻烦的,我们可以简化。

  • 语法2
from 模块 import 属性

看下面的例子

>>> from math import pi
>>> pi
3.141592653589793
>>> math.pi
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    math.pi
NameError: name 'math' is not defined

用这种方法导入的是具体的属性,我们要用模块里面的属性的时候,就直接写属性即可,无需加上模块名了。

  • 其他语法
from 模块 import 属性1,属性2
from 模块 import *
from 模块 import 属性 as 别名

假设你是有点基础的,那么我们来写一个代码test001.py,放到Python主目录的Lib目录下,内容是

#test001.py
#dir:C:\Python37\Lib
age=18
weight=120
height=176
def sayHello():
	print("hello world")

看如下的示例

>>> from test001 import age
>>> age
18
>>> from test001 import height,weight
>>> height
176
>>> weight
120
>>> from test001 import sayHello as sh
>>> sayHello()  #调用原名是失败的
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    sayHello()
NameError: name 'sayHello' is not defined
>>> sh  #只写函数名返回地址
<function sayHello at 0x0000000002EA6A60>
>>> sh()  
hello world
  • 语法4 如何导入文件夹中的呢?
from 文件夹1.文件夹2.文件夹3 import 属性

我们举2个例子: (1)有如下文件 C:\Python37\Lib\xml\sax\saxutils.py,该文件中定义了一个方法

def escape(data, entities={}):
  ...

我们可以这样导入

>>> from xml.sax.saxutils import escape
或者
>>> from xml.sax import saxutils

(2)比如我们selenium中要导入鼠标事件,是这样写的: from selenium.webdriver.common.action_chains import ActionChains

那我们来看看实际存储的路径是怎样的?

C:\Python37\Lib\site-packages\selenium\webdriver\common\action_chains.py
在这个文件中有个定义
class ActionChains(object):
  ...

从上面的2个例子中可以看出来,一个模块的导入可以从好像起始路径是不一样的 C:\Python37\Lib\site-packages
C:\Python37\Lib
其实模块的导入的跟命令执行的原理是类似的,也有一个叫PATH的东西

>>> import sys
>>> sys.path
['', 'C:\\Users\\Tanya\\AppData\\Local\\Programs\\Python\\Python37\\lib', 
'C:\\Users\\Tanya\\AppData\\Local\\Programs\\Python\\Python37', 
'C:\\Users\\Tanya\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages', ]

这个sys.path里面的路径是模块可以导入的搜寻路径,第一个值是空的,其实就是当前目录。 sys.path是一个list类型的,如果要增加一个目录,可以用list的方法来实现,但是临时的,如果要永久的,需要用到SYSPATH的系统变量,这里就不多说了。

3.2 安装模块

如果是第三方模块,那我们就需要安装他们,安装有很多的方法。

3.2.1 pip安装

安装了python后,默认会安装pip,在python主目录下的scripts文件夹下。

image.png

C:\Users\Tanya>pip -h

Usage:
  pip <command> [options]

Commands:
  install                     Install packages.#安装
  uninstall                   Uninstall packages.#卸载
  list                        List installed packages.#列出已安装的包
  show                        Show information about installed packages.#查询安装包信息
  search                      Search PyPI for packages.#搜索安装包

如果我们要安装一个模块,直接输入如下命令即可:

pip install 模块名
比如:
  pip install selenium
  pip install pywin32

但是这种方法安装的包是从pypi.org去下载的,在国内网速如果不够,那下载经常会遇到time out的超时。 其实我们可以指定国内源安装:

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/ 
豆瓣:http://pypi.douban.com/simple/
还有其他网易、搜狐都有可以自行搜索,阿里云用的比较多吧。

语法是这样的

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspider --trusted-host https://pypi.tuna.tsinghua.edu.cn

这样是临时的,如果要永久就需要新建配置文件

  • Windows 在 %USERPROFILE%目录下新建一个pip目录,再新建一个文件pip.ini 内容类似于
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
  • Linux 在用户家目录下新建一个.pip目录,然后新建一个pip.conf文件,内容
[global]
trusted-host=mirrors.aliyun.com
index-url=https://mirrors.aliyun.com/pypi/simple/

3.2.2 setup.py安装

有时候我们无法上网,那我们可以下载号一些安装包,比如selenium-3.141.0.tar.gz 解压后得到类似这样的信息

image.png

那我们可以在windows下可以用cmd来安装

python setup.py install

3.2.3 pycharm安装

(1) File-settings

image.png

Project-Project Interpreter,点击右侧的+

image.png

还有比如whl文件也可以安装,不过应该很少用吧,安装方法跟setup.py是类似的,可以自行搜索

4. 跟模块好像无关的__main__

第一个代码stumain.py

age = 40
print("main外面")
if __name__ == '__main__':
    print("main里面")

在Pycharm中运行结果如下:

main外面
main里面

第二个代码stumain2.py

import stumain
print(stumain.age)
print(__name__)

运行结果如下:

main外面
40
__main__

看这2个结果:你应该能分析出来点什么了

  1. __name__是一个系统定义的值,具体是啥可以自己去查查(后面有空整理)
  2. 如果__name__是main,那么就会执行if条件成立语句
  3. 导入模块的时候会执行代码,但if语句可以判断,如果__name__==main,意味着是自己,那就可以执行下面的代码,如果不是自己(被别的模块导入的),那么就不会执行下面的代码了。 也有的地方叫这个是主函数入口,JAVA的说法,可以这么理解吧。