How to properly use relative or absolute imports in Python modules?

前端 未结 6 1481
我在风中等你
我在风中等你 2020-12-02 20:30

Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: ValueError: Att

6条回答
  •  伪装坚强ぢ
    2020-12-02 21:21

    You could just start 'to run the modules as standalones' in a bit a different way:

    Instead of:

    python foo/bar.py
    

    Use:

    python -mfoo.bar
    

    Of course, the foo/__init__.py file must be present.

    Please also note, that you have a circular dependency between foo.py and bar.py – this won't work. I guess it is just a mistake in your example.

    Update: it seems it also works perfectly well to use this as the first line of the foo/bar.py:

    #!/usr/bin/python -mfoo.bar
    

    Then you can execute the script directly in POSIX systems.

提交回复
热议问题