I have a python program that is entirely contained in a directory with the following structure:
myprog/
├── __init__.py
├── __main__.py
├── moduleone.py
└──
So, having looked at the other responses and not being thrilled, I tried:
from __init__ import *
from my __main__.py
file.
I suppose it doesn't allow you to refer to the module by name, but for simple cases it seems to work.
Do I have to import these functions into
__main__
somehow?
Yes. Only items in builtins
are available without an import. Something like:
from myprog import func1, func2
should do the trick.
If you don't have myprog
installed in the normal python path then you can work around it with something like:
import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
from myprog import function_you_referenced_from_init_file
Which, quite frankly, is horrid.
I would suggest going with MartijnPieters suggestion and put the -m
on the command line, in which case __main__.py
can look like:
from myprog import function_you_referenced_from_init_file
The __init__.py
is only loaded when you are import the package. You are instead treating the directory as a script, by executing the directory.
You can still treat the package as a script, instead of the directory however. To both treat the directory as a package and as the main script, by using the -m
switch:
python -m myprog