【问题标题】:No module found error when using file in same folder in VS Code在 VS Code 中使用同一文件夹中的文件时未发现模块错误
【发布时间】:2020-07-22 16:11:37
【问题描述】:

我正在用 VS Code 编写 Webscraping 应用程序。 Pytho 版本是 3.9。

我在 VS Code 中的文件夹结构

BeautifulSoup - Scraping_Quotes - locator BeautifulSoup -Scraping_Quotes - Parsers

定位器目录有一个 quote_locators.py,其中有一个名为 QuoteLocator 的类。

当我尝试在 Parsers 目录中的 quote.py 中导入此类时,如下代码所示,我收到“No Module Named locator”错误。代码复制如下。

from locator.quote_locators import QuoteLocators

class QuoteParser:
    """ 
    Given one of the specific Quote divs, find out the data about the quote
    """
    def __init__(self, parent):
        self.parent = parent
    
    def __repr__(self):
        return f'<Quote> {self.content}, by {self.author}>'

    @property
    def content(self):
        locator = QuoteLocators.CONTENT
        return self.parent.select_one(locator).string

    @property
    def author(self):
        locator = QuoteLocators.AUTHOR
        return self.parent.select_one(locator).string

    @property
    def tags(self):
        locator = QuoteLocators.TAGS
        return self.parent.select_one(locator)

我的 launch.json 文件(如果相关)有:

"version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}"
        }
    ]

相同的代码在 Pycharm 中完美运行。

即将放弃VSCode,感谢任何帮助!!!

我在 StackOverflow 中尝试了多个建议,但没有任何效果。

【问题讨论】:

    标签: python class visual-studio-code module


    【解决方案1】:

    尝试将以下代码添加到文件'quote.py'中,并更改

    'from locator.quote_locators import QuoteLocators'到'from quote_locators import QuoteLocators'。

    像这样:

    from os.path import dirname, abspath, join
    import sys
    
    # Find code directory relative to our directory
    THIS_DIR = dirname(__file__)             # Returns the full path of the script.
    CODE_DIR = abspath(join(THIS_DIR, '..', 'locator'))     # Returns the absolute path.
    sys.path.append(CODE_DIR)            # Import the required path.
    
    from quote_locators import QuoteLocators
    

    Python从'sys.path'中寻找模块,我们可以通过'append'给它添加模块,

    当使用相对路径搜索时,python 会在当前工作目录中搜索。如果找不到,就会报错。因此,我们可以使用绝对路径来方便其查找。

    另外,注意文件名和类名的拼写,检查文件名是否重命名。

    【讨论】:

      【解决方案2】:

      问题出在我的 .env 文件以及 `settings.json 中。在更正这些以指向正确的路径后,系统可以从不同的文件夹导入模块。

      【讨论】:

      • 你能更详细地解释一下你在这里做了什么吗?几天来我一直在努力解决同样的问题,但无法弄清楚。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 2021-01-21
      • 2018-03-16
      • 2021-04-26
      • 2019-09-02
      相关资源
      最近更新 更多