Python3: Attempted relative import in non-package

空扰寡人 提交于 2019-11-29 11:42:35

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.

GeoStoneMarten

This is not really the subject but for testing your code I would suggest that take a look at this article Testing your code and this topic for Test and python package structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!