当使用 -m 运行 python 脚本时,为什么不调用 __init__.py?

Flo*_*ker 5 python python-2.7

我有一个这样的目录结构:

root/
    __init__.py
    moduleA/
        __init__.py  # prints "hello"
        myscript.py
Run Code Online (Sandbox Code Playgroud)

如果我python -m moduleA.myscriptroot目录运行,hello将会打印出来。但是,如果我python -m myscriptmoduleA目录运行,则不会。

__init__.py为什么执行时当前目录下的which没有python -m被调用?

Rah*_*K P 0

从你的问题我了解到__init__.py里面moduleA有打印你好代码。

因此,当您从根目录执行时,该__init__.py文件将起作用。但是当你进入目录时。该文件将无法工作。

通过使用该python -m module选项,它的工作原理与其他选项相同python module.py

阅读__init__.py

  • 那么,当使用“python -m”并在当前目录中指定脚本时,实际上没有办法运行与包相关的文件吗? (3认同)