英文:
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
,这是一个查找文件的位置列表。默认情况下,它由以下组成:
- 当前目录或执行文件的目录
- 您的
PYTHONPATH
- 您的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:
- The current directory or the directory where the file executed is
- Your
PYTHONPATH
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论