如何导入模块但忽略包的__init__.py? [英] How to import a module but ignoring the package's __init__.py?

查看:80
本文介绍了如何导入模块但忽略包的__init__.py?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试导入Python包内模块中的函数,但是当我尝试执行此操作时:

I'm trying to import a function which is in a module inside a package in Python, but when I try:

from package.module import some_function

Python执行程序包的_ init _.py,但不会发生.

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?

推荐答案

答案为否,如果不执行__init__.py,则无法导入python包.按照定义,要打包,您必须在该目录中放置__init __.py.

The answer is No, you can't import a python package without the __init__.py being executed. 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.

如果只想从模块中导入功能,则可以使用:

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.

这篇关于如何导入模块但忽略包的__init__.py?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆