路径错误 ImportError: 尝试使用未知的父包进行相对导入

3

像下面这样的项目

server
├── celery.py
├── tasks.py

tasks.py

from __future__ import absolute_import, unicode_literals
from sys import path 
from .celery import app_celery
from time import sleep


@app_celery.task
def my_func():
    sleep(5)
    print("Process finished")

celery.py

from __future__ import absolute_import, unicode_literals
from celery import Celery

app_celery = Celery('server',
             broker='redis://',
             backend='redis://',
             include=['server.tasks'])

app_celery.conf.update(
    result_expires=3600,
)

if __name__ == '__main__':
    app_celery.start()

celery -A server worker -l info 启动良好,可以像下面这样进行测试,并且一切都完美无误。

$ ipython
Python 3.7.4 (default, Aug 13 2019, 20:35:49) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from server.tasks import my_func                                                                                                                     

In [2]: my_func.delay()                                                                                                                                      
Out[2]: <AsyncResult: 39a21329-0e80-4f6e-ac08-536832414756>

我想在server下添加一个脚本test.pytest.py
from tasks import my_func

my_func.delay()

当我在服务器下运行python test.py时,它会报告。
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    from tasks import my_func
  File "/xxx/server/tasks.py", line 3, in <module>
    from .celery import app_celery
ImportError: attempted relative import with no known parent package
1个回答

2
在您的服务器目录中添加一个__init__.py文件。这个文件可以是空的。
Python只允许在常规包中使用相对导入。常规包被定义为包含__init__.py文件的目录。 https://docs.python.org/3/reference/import.html

1
谢谢您的帮助,它仍然报告相同的错误。 - ComplicatedPhenomenon
@ComplicatedPhenomenon,你确定文件名打对了吗?两端都是双下划线。 - wxker
1
我再检查一遍,是的。 - ComplicatedPhenomenon
1
@ComplicatedPhenomenon 尝试将 celery.py 重命名为其他名称。它与实际的 Celery 软件包冲突,可能是问题的原因之一。 - wxker
2
当我将celery.py更改为celery_1.py并进行其他相关更改时,错误仍然保持不变。(from .celery_1 import app_celery ImportError: attempted relative import with no known parent package - ComplicatedPhenomenon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接