Beaker is not a part of python standard library, and I want to make my application has no dependencies rather than the python standard library itself. To accomplish this, I download beaker and extract as a sub-package of my application.
Then, I use this:
import os, inspect, sys
sys.path.append(os.path.abspath('./beaker'))
import beaker.middleware
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
And get this error
Traceback (most recent call last):
File "start.py", line 8, in <module>
from kokoropy import kokoro_init
File "/home/gofrendi/workspace/kokoropy/kokoropy/__init__.py", line 9, in <module>
import beaker.middleware
File "/home/gofrendi/workspace/kokoropy/kokoropy/beaker/middleware.py", line 11, in <module>
from beaker.cache import CacheManager
ImportError: No module named beaker.cache
The problem is laid on beaker.middleware line 11:
from beaker.cache import CacheManager
The interpreter cannot recognize beaker package since it is not installed Actually I can fix that by change that line into this:
from cache import CacheManager
But by doing that, I need to modify a lot.
So, is there any way to use beaker without install it and without doing too many modification?
PS: Below is my directory structure
kokoropy
|
|--- __init__.py <-- this is where I write my script
|
|--- beaker
|
|--- __init__.py
EDIT: The accepted answer is correct, but in my case, I run the script at one-level top directory. Therefore, below solution seems to be more robust:
import os, inspect, sys
sys.path.append(os.path.dirname(__file__))
Or maybe this: How do I get the path of the current executed file in Python? :)
You have to add the directory that contains the beaker
directory
to the path not the beaker directory itself:
<root>
|
--beaker
|
-- <...>
In this case you need to add the <root>
directory to the path.
According to your example code this would be:
sys.path.append(os.path.abspath('.'))
Which probably means that you run your program from this folder,
which would add it to the PYTHONPATH
automatically.
(So it should run without you modifying the PYTHONPATH
at all).
EDIT:
For more information on the topic you can checkout the Python docs about modules: Modules in python.