简体   繁体   English

Python-包名称相同时从文件导入

[英]Python - import from a file when a package has the same name

I did something silly when I started my python project: I named my main file project.py, and I stored a bunch of logic in a package that is also called project. 启动python项目时,我做了一些愚蠢的事情:我将主文件命名为project.py,并将一堆逻辑存储在一个也称为project的程序包中。 Here's the directory structure: 这是目录结构:

project.py
project/
    other files

Here's the problem: Now I need to import the function main from project.py. 问题出在这里:现在我需要从project.py导入main函数。 But every time I try to import it, python tries to import the package instead of the module. 但是每次我尝试导入它时,python都会尝试导入包而不是模块。

>>> from project import main
AttributeError: 'module' object has no attribute 'main'
>>> import project
>>> print(project)
>>> <module 'project' from 'c:\temp\project\__init__.pyc'>

Is there any way to fix this without renaming either the folder or the file? 有什么方法可以解决此问题而无需重命名文件夹或文件?

Right now, my solution is to move the logic from project.py to a new file: 现在,我的解决方案是将逻辑从project.py移到新文件:

project.py
project/
    main.py

contents of project.py: project.py的内容:

import project.main
if __name__ == "__main__":
    project.main.main()

Then I can import project.main.main() directly. 然后,我可以直接导入project.main.main()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 模块同名时导入python包 - import python package when module is same name 当 package 与 package 中的 .py 文件同名时, import X 导入模块而不是 package 本身。 如何避免? - When package has same name as .py file inside the package, import X imports the module and not the package itself. How to avoid? Python 和 package 同名时导入错误 - Import error when Python and package have same name Python:从兄弟目录导入文件,其中父目录具有相同的名称 - Python: import file from sibling directory, where parent directory has the same name Python3 包文件在不同目录下使用时无法从同一目录导入 - Python3 package file cannot import from same directory when used in a different directory 如何导入与带有子包和模块的纯python包同名的python扩展模块? - How to import python extension module that has the same name as a pure python package with subpackages and modules? 从具有相同名称的脚本导入已安装的 package 引发“AttributeError:模块没有属性”或“ImportError:无法导入名称” - Importing installed package from script with the same name raises "AttributeError: module has no attribute" or "ImportError: cannot import name" Python在同一个包中的__init__.py中导入类 - Python Import class in __init__.py from file in same package Python:尝试从同一 package 导入模块时出现“ModuleNotFoundError” - Python: 'ModuleNotFoundError' when trying to import module from the same package 如何导入站点包的模块而不是当前目录中具有相同名称的模块(python 3.x)? - How to import site package's module instead of one in current directory that has the same name (python 3.x)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM