python中的文件导入

a.py的代码

# from B import b
from C import c
import sys
# for i in sys.path:
#     print(i)
def a_1():
    print('This is a')


c.c_1()

b.py的代码

def b_1():
    print("This is b")

c.py的代码

import sys 
sys.path.append('/data/qh_20T_share_file/zqy/code/Test/B/')
from b import b_1


# print(sys.path)


def c_1():
    print("This is c")
    b_1()
    print(sys.path)
if __name__ == '__main__':
    c.c_1()
    b_1()

运行a.py会输出

his is c
This is b
['/data/qh_20T_share_file/zqy/code/Test', '/data/qh_20T_share_file/share/Anaconda3/lib/python37.zip', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7/lib-dynload', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7/site-packages', '/data/qh_20T_share_file/zqy/code/Test/B/']

可以看到输出的路径加上了'/data/qh_20T_share_file/zqy/code/Test',及a.py的父目录。要想在def c_1函数中成功导入b_1(),可以写成from B import b,也是可以成功运行的。因为B在'/data/qh_20T_share_file/zqy/code/Test'路径下,可以直接找到。

 如果将c.py的代码改为

import sys

# sys.path.append('/data/qh_20T_share_file/zqy/code/Test/B/')

from B.b import b_1

# print(sys.path)

def c_1():

    print("This is c")

    b_1()

    print(sys.path)

if __name__ == '__main__':

    b_1()

运行就会报错

[Running] python -u "/data/qh_20T_share_file/zqy/code/Test/C/c.py"

Traceback (most recent call last):

  File "/data/qh_20T_share_file/zqy/code/Test/C/c.py", line 3, in <module>

    from B.b import b_1

ModuleNotFoundError: No module named 'B'

我们可以输出引用的环境

['/data/qh_20T_share_file/zqy/code/Test/C', '/data/qh_20T_share_file/share/Anaconda3/lib/python37.zip', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7/lib-dynload', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7/site-packages']

可以看到并不包含B模块的父目录,我们可以通过加入父目录来运行。代码如下

import sys 
sys.path.append('/data/qh_20T_share_file/zqy/code/Test/')
from B.b import b_1


print(sys.path)


def c_1():
    print("This is c")
    b_1()
    print(sys.path)
if __name__ == '__main__':
    b_1()

输出为

['/data/qh_20T_share_file/zqy/code/Test/C', '/data/qh_20T_share_file/share/Anaconda3/lib/python37.zip', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7/lib-dynload', '/data/qh_20T_share_file/share/Anaconda3/lib/python3.7/site-packages', '/data/qh_20T_share_file/zqy/code/Test/']
This is b

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值