如何在文件包含来自不同目录的模块时运行 Python 脚本?

huangapple go评论90阅读模式
英文:

How to run a python script when a file contains a module from different directory?

问题

我有以下的结构:

|-- master.py
|-- src
| |-- configs
| | |-- init.py
| | |-- config.py
|-- convert_speech
| |-- init.py
| |-- record_audio2.py


现在我想在record_audio2.py脚本中从configs.config中导入一个模块。我成功地使用以下方式做到了这一点:

from src.configs.config import filenames


然而,当我运行master.py时,我得到以下错误:

*ModuleNotFoundError: No module named 'src'*

我希望能够通过运行master.py来运行所有内容,以及单独运行record_audio2.py。目前只有record_audio2.py成功运行。
英文:

I have the following structure:

|-- master.py
|-- src
| |-- configs
| | |-- _init_.py
| | |-- config.py
|-- convert_speech
| |-- _init_.py
| |-- record_audio2.py

Now I want to import a module from configs.config into the record_audio2.py script. I managed it to do that using this:

from src.configs.config import filenames

However when I run master.py I get the following error:

ModuleNotFoundError: No module named 'src'

I would like to be able to run everything by running master.py as well as running record_audio2.py individually. Right now only record_audio2.py runs successfully.

答案1

得分: 0

首先,要让Python将目录视为模块,它们必须包含一个名为__init__.py的文件。

现在,当Python处理模块导入时,它使用sys.path,这是一个查找文件的位置列表。默认情况下,它由以下组成:

  1. 当前目录或执行文件的目录
  2. 您的PYTHONPATH
  3. 您的Python实例的安装文件夹

关于这方面的更多信息,请参阅文档

我建议您将src文件夹的路径添加到sys.path,应该像这样工作。

英文:

First of all, to make Python treat directories as modules, they must have an __init__.py file in them.

Now, when Python treats imports of modules, it uses sys.path which is a list of places where to look for the files. By default, it is composed of:

  1. The current directory or the directory where the file executed is
  2. Your PYTHONPATH
  3. The installation folder of your python instance

More on that here in the doc.

I suggest you add the path to the src folder to the sys.path, it should work like this.

答案2

得分: 0

尝试这个:

import ..configs.config import filename
英文:

Try this:

import ..configs.config import filename

huangapple
  • 本文由 发表于 2020年1月3日 19:26:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定