简体   繁体   English

如何导入模块但忽略包的 __init__.py?

[英]How to import a module but ignoring the package's __init__.py?

I'm trying to import a function which is in a module inside a package in Python, but when I try:我正在尝试导入 Python 包内模块中的函数,但是当我尝试时:

from package.module import some_function

Python executes the package's _ init _.py but it can't happen. Python 执行包的 _ init _.py 但它不会发生。

Is there a way to import the function telling Python to ignore the package's _ init _.py?有没有办法导入告诉 Python 忽略包的 _ init _.py 的函数?

The answer is No, you can't import a python package without the __init__.py being executed.答案是否定的,如果不执行 __init__.py 就不能导入 python 包。 By definition, to make a package, you must put in that directory a __init__.py.根据定义,要制作一个包,您必须在该目录中放入一个 __init__.py。

But, you can make an empty __init__.py file.但是,您可以创建一个空的 __init__.py 文件。

If you want just to import a function from a module, you can use:如果你只想从模块中导入一个函数,你可以使用:

import sys
sys.path.append('path_to_package/')

from module import some_function

Note that this is a dirty solution, and won't always work.请注意,这是一个肮脏的解决方案,并不总是有效。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM