Python3: Attempted relative import in non-package

前端 未结 1 951
渐次进展
渐次进展 2021-01-14 10:45

I\'m so sorry about this basic question, because it\'s similar to this: Stumped by relative imports

But I\'m trying to follow the PEP328 http://www.python.org/dev/pe

相关标签:
1条回答
  • 2021-01-14 11:13

    You cannot use a script within a package; you are running test, not test.test. A top-level script can thus not use relative imports.

    If you wanted to run a package as a script, you'd need to move test/test.py to testpackage/__main__.py, move one directory up in your shell to ~/Desktop and tell python to run a package with python -m testpackage.

    Demo:

    $ ls testpackage/
    __init__.py   __main__.py   __pycache__   controller.py
    $ cat testpackage/controller.py 
    class Controller:
        def __init__(self):
            pass
    
    $ cat testpackage/__init__.py 
    # -*- coding: utf-8 -*-
    
    $ cat testpackage/__main__.py 
    from .controller import Controller
    if __name__ == '__main__':
        print('running...')
    
    $ python3.3 -m testpackage
    running...
    

    You cannot name the package test; Python already has such a package for the test suite and that'll be found before a package in the current working dir is found.

    The alternative is to create a script outside of the package and import the package from the script.

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