Relative imports in Python 3

前端 未结 16 1303
误落风尘
误落风尘 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:11

    TLDR; Append Script path to the System Path by adding following in the entry point of your python script.

    import os.path
    import sys
    PACKAGE_PARENT = '..'
    SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
    sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
    

    Thats it now you can run your project in PyCharma as well as from Terminal!!

提交回复
热议问题