Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import your package/modules from a script in bin folder in python

Tags:

python

When organising python project, this structure seems to be a standard way of doing it:

myproject\     bin\         myscript     mypackage\         __init__.py         core.py     tests\         __init__.py         mypackage_tests.py setup.py 

My question is, how do I import my core.py so I can use it in myscript?

both __init__.py files are empty.

Content of myscript:

#!/usr/bin/env python from mypackage import core if __name__ == '__main__':     core.main() 

Content of core.py

def main():     print 'hello' 

When I run myscript from inside myproject directory, I get the following error:

Traceback (most recent call last):   File "bin/myscript", line 2, in <module>     from mypackage import core ImportError: No module named mypackage 

What am I missing?

like image 483
tim_wonil Avatar asked Jul 23 '12 12:07

tim_wonil


People also ask

How do you import a module from a package Python?

Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.


1 Answers

Usually, setup.py should install the package in a place where the Python interpreter can find it, so after installation import mypackage will work. To facilitate running the scripts in bin right from the development tree, I'd usually simply add a simlink to ../mypackage/ to the bin directory. Of course, this requires a filesystem supporting symlinks…

like image 189
Sven Marnach Avatar answered Oct 23 '22 16:10

Sven Marnach