How To Properly Write The Import Statement
Solution 1:
if your script is using lib
you can create a setup.py
using file for your project using setuptools
Using setuptools develop
command will create a "development mode" version of your project and put it on your python path. It then becomes easy to use it like you would use any python package.
your setup.py can be as simple as:
from setuptools import setup, find_packages
setup(
name = "lib",
version = "0.1dev",
packages = find_packages(),
)
Then you can develop on your project like
python setup.py develop
Now you can import your package into any script you want
from lib.model import model
Solution 2:
If lib
is a package, run myscript
as a module and import mymodel
like this:
from ..model import mymodel # relative import
Or:
from lib.model import mymodel # absolute import
To run myscript.py
as a module in the lib
package, do one of the following:
- run a program in the folder containing
lib
that importslib.myscript.myscript
- run
myscript.py
as a module from the folder containinglib
, usingpython -m lib.myscript.myscript
Solution 3:
Assuming you call from myscript.py
.
Try this:
import sys
sys.path.insert(0, '../model/')
import mynodel
mynodel
is probably mymodel
, I think you made a typo in your post.
Never put the extension at the imprt statement.
sys.path
is a list of paths where python will look for library files. You can simply add a relative path to the directory you want. By putting it at the front of the list, you ensure that python will first look for the file at the specified path (say for instance there is a library with the same name, your file will have priority).
Furthermore it could be useful to give the output of tree
(a linux and cmd
(Windows) command). This gives standardized output.
Post a Comment for "How To Properly Write The Import Statement"