最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kubernetes - Python 3 relative imports behave differently between local run and on k8s - Stack Overflow

programmeradmin2浏览0评论

I have the following structure:

project/
  |- src/
       |- __init__.py
       |- package/
             |- __init__.py
             |- module1.py
             |- module2.py

Let's say module1.py tries to import a symbol from module2:

from .module2 import MySymbol

Run it locally with python <filename>.py and this hits the error: ImportError: attempted relative import with no known parent package whether I run it from project or from project/src/package. I try:

from src.package.module2 import MySymbol

and it complains no module named src...

When it runs in a k8s cluster, it hits the error without a . prefix:

ModuleNotFoundError: No module named 'module1'

This is a dilemma for me because importing local module in the same folder using . prefix works when the app runs in k8s pod. However, this doesn't run locally. How to get the best of these 2 worlds?

I have the following structure:

project/
  |- src/
       |- __init__.py
       |- package/
             |- __init__.py
             |- module1.py
             |- module2.py

Let's say module1.py tries to import a symbol from module2:

from .module2 import MySymbol

Run it locally with python <filename>.py and this hits the error: ImportError: attempted relative import with no known parent package whether I run it from project or from project/src/package. I try:

from src.package.module2 import MySymbol

and it complains no module named src...

When it runs in a k8s cluster, it hits the error without a . prefix:

ModuleNotFoundError: No module named 'module1'

This is a dilemma for me because importing local module in the same folder using . prefix works when the app runs in k8s pod. However, this doesn't run locally. How to get the best of these 2 worlds?

Share Improve this question edited Mar 16 at 7:02 khteh asked Mar 15 at 7:57 khtehkhteh 4,05810 gold badges59 silver badges104 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You should be running your script from the project folder - as in:

$ cd /path/to/project
$ python -m src.package.module1 # or whatever filename is but *without* the .py

Then both absolute and relative import forms will work.

发布评论

评论列表(0)

  1. 暂无评论