Python relative imports within a package not on the path

前端 未结 2 1998
北恋
北恋 2021-01-13 15:28

How can I import a file that is in a parent directory within a python package (that is not on the path) into a file in a child dir?

I\'m not totally clear on the voc

2条回答
  •  抹茶落季
    2021-01-13 15:54

    You can actually do this:

    import sys
    sys.path.append('..')
    

    and that will work. But don't do that. It could break other modules.

    I guess you could remove it directly after the import, but don't.

    EDIT:

    Actually, this also works and I think there's no reason it's not safe:

    inside in_dir2.py you can do:

    import sys
    import os
    current_module = sys.modules[__name__]
    indir2file=current_module.__file__
    sys.path.append(os.path.dirname(os.path.abspath(indir2file))+os.sep+".."+os.sep)
    import in_dir1
    

    Try hard to restructure your code instead.

提交回复
热议问题