Module and Package *****************************
First, the module
In Python, a. py file is called a module.
? greatly improve the maintainability of the Code;
? Writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere;
Classification:
1). built-in modules :
2). third-party modules
(Unofficial, relatively good open source module, URL: pypi.python.org, the pip install module name at the time of installation)
3). Custom Modules
Create a module
Writing a Python script
2. Import the module
1). Import Script Name
Note: Under the same directory
Module naming as short as possible, in all lowercase, you can use the underscore
2). Import as
3). From import
in [+]: From __future__ Import Division Note: The role of the __FUTURE__ module: Experience the features of the new version in the version
Advantages:
1). Improved maintainability of the code
2). Writing code does not have to start from scratch, and when a module is written, it can be referenced elsewhere
3. Scope of the module
Normal functions and variable names in the module are functional, in Python, when some functions and variables do not want to be used by others, through the _ prefix implementation, such as __author__, __name__ is a special variable, __func__,__fun is a private function, can not directly reference
Two. Common modules
1.OS module
in [+]: Import os
In [all]: Os.name #当前所在平台
OUT[23]: ' POSIX '
in [+]: OS.GETCWD () Gets the absolute path of the current location
OUT[24]: '/root/code6 '
2. SYS module
SYS module mainly provides system-related configuration and operation, encapsulating the detection, changing the interpreter runtime and the interaction of resources
Sys.version #得到解释器的版本信息
Sys.platform #得到当前运行平台
SYS.ARGV #获取传递给脚本的参数, parameter parsing is similar to bash, and the first parameter represents the script itself
Sys.path #Python在指定的路径下搜索模块与包对应的路径
Sys.path.append () #添加搜索模块与包的路径
Sys.path.remove () #指定删除搜索模块与包的路径
Sys.path.insert () #指定位置添加索模块与包的路径
3. Random Module
Random.randint () #随机产生指定范围的字符
Random.random () #随机产生0到1之间的小数
Random.uniform () #随机产生指定范围的小数
Random.randrange () #随机产生指定范围字符
Random.choice () #随机在给定范围产生一个
Random.sample () #随机在给定范围产生多个
Random.shuffle () #随机打乱
4. Time Module
Time.time () #时间戳
Time.localtime () #将时间戳转化为元组格式时间
Time.ctime () #时间戳转化为字符串格式显示
Time.strftime () #将元组格式时间转化为字符串显示
Time.strptime () #将字符串显示转化为元组格式时间
in [+]: time.strftime ('%h:%m:%s ')
OUT[63]: ' 07:18:35 '
Time.mktime (t) #将元组格式时间转化为时间戳, but the tuple length must be 9
Time.sleep () #等待时长
Three, the package
1. Create a Package
1). Create a directory for the package name
2). In this directory, create a __init__.py file to store the package information, the file can be empty
Note: When the package is named as short as possible, use all lowercase, you can not use the underscore
Python-Modules and packages