路径错误ImportError:尝试在没有已知父包的情况下进行相对导入

2024-06-25 08:02:51 发布

您现在位置:Python中文网/ 问答频道 /正文

项目如下

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")

芹菜

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.py

test.py

from tasks import my_func

my_func.delay()

当我在server下运行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

Tags: frompytestimportappservermyunicode