Relative imports in Python 3

前端 未结 16 1293
误落风尘
误落风尘 2020-11-21 06:42

I want to import a function from another file in the same directory.

Sometimes it works for me with from .mymodule import myfunction but sometimes I get

16条回答
  •  无人及你
    2020-11-21 07:08

    I had a similar problem: I needed a Linux service and cgi plugin which use common constants to cooperate. The 'natural' way to do this is to place them in the init.py of the package, but I cannot start the cgi plugin with the -m parameter.

    My final solution was similar to Solution #2 above:

    import sys
    import pathlib as p
    import importlib
    
    pp = p.Path(sys.argv[0])
    pack = pp.resolve().parent
    
    pkg = importlib.import_module('__init__', package=str(pack))
    

    The disadvantage is that you must prefix the constants (or common functions) with pkg:

    print(pkg.Glob)
    

提交回复
热议问题