【问题标题】:How to use helper files in PyCharm如何在 PyCharm 中使用帮助文件
【发布时间】:2020-11-06 06:48:02
【问题描述】:

我正在尝试跟随project written by Mike Smales - "Sound Classification using Deep Learning"。在那里,作者编写了一个名为 wavfilehelper.py 的帮助文件:

wavehelper.py 代码

import struct

class WavFileHelper():
    
    def read_file_properties(self, filename):

        wave_file = open(filename,"rb")
        
        riff = wave_file.read(12)
        fmt = wave_file.read(36)
        
        num_channels_string = fmt[10:12]
        num_channels = struct.unpack('<H', num_channels_string)[0]

        sample_rate_string = fmt[12:16]
        sample_rate = struct.unpack("<I",sample_rate_string)[0]
        
        bit_depth_string = fmt[22:24]
        bit_depth = struct.unpack("<H",bit_depth_string)[0]

        return (num_channels, sample_rate, bit_depth)

在他的主程序中,他这样调用帮助文件:

from helpers.wavfilehelper import WavFileHelper

wavfilehelper = WavFileHelper()

但是,当我在 PyCharm 中运行这段代码时,它会报错“ModuleNotFoundError: No module named 'helpers.wavfilehelper'”...我怎样才能让这个帮助文件在 PyCharm 环境中工作?我是否必须将wavehelper.py 文件放在一个特殊文件夹中才能调用?

任何帮助将不胜感激!

【问题讨论】:

    标签: python pycharm helper


    【解决方案1】:

    查看(并在您的问题中引用)实际的错误消息很重要!在这种情况下,哪一行出错了?这不是实例化行,而是导入 - Python 无法在您的机器上找到模块(使用它的系统路径)。

    在文章的前面,作者谈到了从 GitHub 下载他的文件(到您的机器)。您是否遵循了这一步?

    Web.Ref: further information about solving this error

    【讨论】:

    • 感谢您的意见。我确实下载了帮助文件,目前在文件夹名称 helpers 中有 wavfilehelper.py。有没有办法正确指向帮助文件?因为helpers.wavefilehelper 对我不起作用。
    • 是的。请在docs.python.org/3/library/sys.htmlstackoverflow.com/questions/16114391/… 阅读有关sys.path 的信息
    • 然而,Python 希望在当前目录或其某个子目录中找到导入模块。因此,要么将 helpers 文件夹的内容移动到项目文件夹中,要么将文件夹移动到项目文件夹的子文件夹中(在这种情况下,在导入的模块名称前添加 - directory_name.helpers)。但请注意:您使用“助手”这个名称来表示几个不同的组件!
    【解决方案2】:

    是的,为了按规定运行python main.py程序,它想通过from helpers.wavfilehelper import WavFileHelperhelpers/wavehelper.py导入一个名为WavFileHelper的类

    【讨论】:

    • 感谢您的回答。如何让它在 IDE PyCharm 中工作?如上所述,我收到“无模块”错误。如何修改 main.py 中的行以使用帮助文件?
    • 如何导入wavfilehelper?
    猜你喜欢
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2017-10-15
    • 2023-03-12
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多