Python

包中有一个或多个模块文件

像该目录一样,bin 和 conf 就是包,在 Python2 中有 __init__.py 文件才算是包

导入包

main.py 文件导入 conf 包

__init__.py

def sleep():
    print("I am sleep")

main.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import conf

conf.sleep()

运行结果

在根目录导入包中的模块

程序主入口 main.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from bin import test

test.say()

调用 bin 包下的 test.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def say():
    print("Hello World!")

main.py 运行结果

调用了 bin 包下 test 模块中的 say() 方法

如果 main.py 导入了 bin 包中的 test 模块,test.py 文件也想要导入该目录下的 a 模块

a.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def study():
    print("I am studying")

test.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from bin import a

def say():
    print("Hello World!")

a.study()

main.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from bin import test

test.say()
test.a.study()

运行结果

先执行了 test.py 中的 a.study(),然后执行了 main.py 中的 test.say() 和 test.a.study()

虽然 test.py 和 a.py 是在同一个目录下,但是 test.py 被 main.py 导入后,test.py 导入的模块的路径要跟 main.py 一样

跨目录导入模块

bin 包下的 bin.py 文件想导入 conf 包中的 setting 模块

setting.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def run():
    print('I am running')

bin.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import os
import sys

path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(path)
sys.path.append(path)

from conf import setting

setting.run()

运行结果

__file__ 为该文件的绝对路径,os.path.abspath(__file__) 为该文件的绝对路径,即 C:/Python27/test/1/bin/bin.py

os.path.dirname() 为该文件所在的目录,即为 C:/Python27/test/1/bin/,第二个 os.path.dirname() 为 C:/Python27/test/1/bin/ 所在的目录,即 C:/Python27/test/1/

相对导入模块

. 为当前目录

test.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from . import a  # . 为当前目录,即 bin目录

def say():
    print("Hello World!")

main.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from bin import test

test.a.study()

运行结果

.. 为上一级目录

在 bin 目录下新建一个 lib 目录,并创建文件 test.py

在 bin 目录下新建一个 lib2 目录,并创建文件 b.py

1/bin/lib2/b.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def cry():
    print("I am crying")

1/bin/a.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def study():
    print("I am studying")

1/bin/lib/test.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from .. import a  # .. 为上级目录,即 bin 目录
from ..lib2 import b  # ..lib2 为上级目录下的 lib2 目录,即 bin/lib2 目录

def say():
    print("I am saying")

1/main.py

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

from bin.lib import test

test.say()  # 执行 bin/lib 目录下 test 模块的 say() 方法
test.a.study()  # 执行 bin 目录下 a 模块的 study() 方法
test.b.cry()  # 执行 bin/lib2 目录下 b 模块的 cry() 方法 

运行结果

原文地址:https://www.cnblogs.com/sch01ar/p/9418766.html