import error.py问题

import error.py问题

单独运行utils.py没有问题

运行base.py则ModuleNotFoundError: No module named 'error'

https://img1.sycdn.imooc.com//climg/6476ad72094a62bc15000157.jpg

运行2个脚本都是在utils.py脚本中  import  error.py

utils.py

# coding:utf-8

"""常用的公共函数"""

import os
import error


def check_file(path):
    if not os.path.exists(path):
        raise error.NotPathError(f'not found {path}')

    if not path.endswith('.json'):  # 不是json文件名字
        raise error.FormatError('need json format')

    if not os.path.isfile(path):
        raise error.NotFileError('this is not a file')


if __name__ == '__main__':
    gift_path = os.path.join('../', 'storage', 'gift.json')
    user_path = os.path.join('../', 'storage', 'user.json')
    check_file(gift_path)
    check_file(user_path)

base.py

# coding:utf-8

"""
    1:导入user.json   文件检查
    2:导入gift.json   文件检查
"""

import os
# from common import error
from common.utils import check_file


class Base(object):
    def __init__(self, user_json, gift_json):
        self.user_json = user_json
        self.gift_json = gift_json

        self.__check_user_json()
        self.__check_gift_json()

    def __check_user_json(self):  # 路径不存在
        check_file(self.user_json)

    def __check_gift_json(self):
        check_file(self.gift_json)


if __name__ == '__main__':
    gift_path = os.path.join(os.getcwd(), 'storage', 'gift.json')
    user_path = os.path.join(os.getcwd(), 'storage', 'user.json')
    print(gift_path)
    print(user_path)
    # base = Base(user_path, gift_path)


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
Mr朱_ 提问者 2023-05-31 10:29:25

改成老师的代码提示没有已知的父包

import os
from .error import NotPathError, NotFileError, FormatError

https://img1.sycdn.imooc.com//climg/6476b10309fde69914570138.jpg

  • 同学,你好!1、将util.py 的导包改成

    from common.error import NotPathError, FormatError, NotPathError

    如报错提示系统找不到父包,写上common 父文件夹

    2、导入后util.py中引入error模块的类用如下方法

    https://img1.sycdn.imooc.com//climg/6476b6d309f6486009240437.jpg


    祝学习愉快~

    2023-05-31 10:55:06
  • 提问者 Mr朱_ 回复 好帮手慕小猿 #2

    win环境下   运行base.py时,

    from common.utils import check_file

    同时utils

    from error import NotPathError, NotFileError, FormatError

    那么utils   import 的书写就需要以base.py脚本所在文件夹作为基准,即:

    from common.error import NotPathError, NotFileError, FormatError

    mac的逻辑跟win逻辑不一致,是这么理解吗?

    2023-05-31 11:08:21
  • 好帮手慕小猿 回复 提问者 Mr朱_ #3

    同学,你好!逻辑一样的,有两种导入方式,一个是util.py 导入改成找到父文件夹

    from common.error  import NotPathError, NotFileError, FormatError

    也可以使用.error告诉是同级的error.py

    from .error  import NotPathError, NotFileError, FormatError

    是视频中也是使用这种方法的

    https://img1.sycdn.imooc.com//climg/6476c96d095712d715390757.jpg

    错误在于同学直接import  error ,这种导入模块方式不正确,应使用from .error import .....,或from common .error  import .....

    祝学习愉快~

    2023-05-31 12:16:42
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师