跳转至

Python模块

概要: 如何调用和编写Python模块

创建时间: 2022.10.02 11:26:37

更新时间: 2022.10.02 11:30:50

调用系统模块

很简单,示例程序块如下

Python
1
2
3
4
5
6
7
import sys

print('The command line arguments are')
for i in sys.argv:
    print(i)

print('\n\nThe PYTHONPATH is', sys.path, '\n')

当键入python moudle_using_sys.py we are arguments后,得出如下结果

Text Only
1
2
3
4
5
6
7
8
9
PS E:\sublime text 3 files\python3> python moudle_using_sys.py we are arguments
The command line arguments are
moudle_using_sys.py
we
are
arguments


The PYTHONPATH is ['E:\\sublime text 3 files\\python3', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']

提示

  1. sys模块包含了与Python解释器及其环境相关的功能,即系统功能

  2. 在上述示例中,运行的脚本名称在sys.argv列表中会位列第一,即脚本名称首先显示。而moudle_using_sys.py对应sys.argv[0],除此之外,we,are,arguements分别对应sys.argv[1],sys.argv[2],sys.argv[3]

  3. 通过运行命令>>> import os; print(os.getcwd())可以查看当前程序的目录

from...import语句

为了增强程序的可读性,尽量避免使用此类语句,应该选择使用import语句

模块中的 name

为了确定模块是独立运行的或是被导入进来的,可以通过查看模块的__name__属性来实现

Python
1
2
3
4
if __name__ == '__main__':
    print('This program is being run by itself')
else:
    print('I am being imported from another moudle')
通过键入不同的命令,我们可以查看其是否为导入的模块
Text Only
1
2
3
4
5
6
$ python module_using_name.py
This program is being run by itself
$ python
>>> import module_using_name
I am being imported from another module
>>>

编写模块

首先,创建自己的模块,单独存放为mymodule.py文件

Python
1
2
3
def say_hi():
print('Hi, this is mymodule speaking.')
__version__ = '0.1'

接下来,在相同目录下,创建导入上面模块的程序mymodule_demo.py

Python
1
2
3
import mymodule
mymodule.say_hi()
print('Version', mymodule.__version__)

输出如下

Text Only
1
2
3
PS E:\sublime text 3 files\python3> python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1

提示

如果采用from mymodule import的形式,则会导入诸如say_hi等所有公共名称,但不会导入__version__等以下划线开头的名称

dir 函数:查看属性

参考以下代码

Python
PS E:\sublime text 3 files\python3> python
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys  # 导入sys模块
>>> dir(sys)  # 查看sys模块属性
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']
>>> dir()  # 查看当前模块的属性
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'sys']
>>> a=5  # 创建新的变量'a'
>>> dir()  # 发现'a'已经加入当前模块
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'sys']
>>> del a  # 删除变量'a'
>>> dir()  # 查看当前模块的属性,'a'消失了
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'sys']

提示

  1. 被导入进来的模块所生成的列表也将成为i此列表的一部分

  2. del语句将直接抹除一个变量或者属性(如'a')

package 包

包的作用:打包组织起来一些模块,如下面的文件夹的分层结构

Text Only
- <some folder present in the sys.path>/
    - world/
        - __init__.py
        - asia/
            - __init__.py
            - india/
                - __init__.py
                - foo.py
    - africa/
        - __init__.py
        - madagascar/
            - __init__.py
            - bar.py