Python3 submodules setup does not update paths when run with -m switch

前端 未结 1 1904
感动是毒
感动是毒 2020-12-21 14:16

I have the following project structure:

server/
   server.py
   __init__.py

   sockets/
      module.py
      __init__.py

I set PYTH

相关标签:
1条回答
  • 2020-12-21 14:49

    The behaviour is entirely correct; sockets is not a top-level module. However, when you use $PYTHONPATH/server/server.py, Python also adds $PYTHONPATH/server/ to the Python search path, so now sockets is a top-level module. You should never directly run files in a package.

    Import sockets relative to the current package:

    from . import sockets
    from .sockets.module import Module 
    

    or use fully-qualified imports:

    from server import sockets
    from server.sockets.module import Module 
    

    Also see the Interface Options section of the Python Setup and Usage section in the fine manual:

    If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.

    Note that the -m switch takes a python identifier, not a filename, so use:

    python -m server.server
    

    leaving of the .py extension.

    0 讨论(0)
提交回复
热议问题