如果我将一个 Python 模块实现为一个目录(即包),它同时具有顶级函数 run
和子模块 run
,我可以指望 from example import run
总是导入函数?根据我的测试,至少在 Linux 上使用 Python 2.6 和 Jython 2.5 是这样,但我通常可以指望它吗?我尝试搜索有关导入优先级的信息,但找不到任何内容。
背景:
我有一个相当大的包,人们通常将其作为工具从命令行运行,但有时也以编程方式使用。我想为这两种用法提供简单的入口点,并考虑像这样实现它们:
示例/__init__.py
:
def run(*args):
print args # real application code belongs here
example/run.py
:
hệ thống nhập khẩu
from example import run
run(*sys.argv[1:])
第一个入口点允许用户像这样从 Python 访问模块:
from example import run
run(args)
后一个入口点允许用户使用以下两种方法从命令行执行模块:
python -m example.run args
python path/to/example/run.py args
这两个都很好用,涵盖了我需要的一切。在将其付诸实际使用之前,我想知道这种方法是否适合所有操作系统上的所有 Python 实现。
我认为这应该始终有效;函数定义将隐藏模块。
然而,这也让我觉得这是一个肮脏的 hack。干净的方法是
# __init__.py
# re-export run.run as run
from .run import run
即,一个最小的 __init__.py
,所有运行逻辑都在 run.py
中:
# run.py
def run(*args):
print args # real application code belongs here
if __name__ == "__main__":
run(*sys.argv[1:])
Tôi là một lập trình viên xuất sắc, rất giỏi!