开发者

Relative import from current file

开发者 https://www.devze.com 2023-03-20 14:32 出处:网络
Currently I have a \"main\" folder where all of the modules I write eventually go, but I usually place the modules I\'m currently working on in a \'dev\' folder just so I don\'t clutter up the other f

Currently I have a "main" folder where all of the modules I write eventually go, but I usually place the modules I'm currently working on in a 'dev' folder just so I don't clutter up the other folder with stuff that aren't ready.

The structure looks like this

MyProg
|-run.py
|-\lib
| |-someLibrary.py
| ...
|
|-\main
| |-readyScripts.py
| ...
|
|-\dev
  |-inProgress.py

Run.py will import scripts from the main folder.

Scripts in the main folder use relative imports to import someLibrary from the lib folder, and it works fine.

However, it doesn't work when I'm still writing my program in the dev folder and running it directly from there (ie: python inProgress.py), saying that I "attempted relative import in non-package"

Is there a way to be able to import modules from the lib folder while I am working on scripts in dev?

EDIT: this is my import statement in inProgress.py:

from .lib impor开发者_如何学Pythont someLibrary

Ideally, I would like to keep it this way so that when I move it to the main folder, I won't have to do anything to the import statement.


If you have your PYTHONPATH set to MyProg, what you can do is create an empty __init__.py file in each folder so python recognizes them as modules:

MyProg
|-run.py
|-__init__.py
|-\lib
| |-someLibrary.py
| |-__init__.py
| ...
|
|-\main
| |-readyScripts.py
| |-__init__.py
| ...
|
|-\dev
| |-inProgress.py
| |-__init__.py

So in your inProgress.py file, you could use:

import lib.someLibrary

In your run.py you could do this:

import main.readyScripts
import dev.inProgress


One option is to import is by using their path:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()


Set your PYTHONPATH to one level up, and then run it with the package syntax?

0

精彩评论

暂无评论...
验证码 换一张
取 消