I’ve got a python script, which should read a subdirectory and make all the scripts within it callable like this:
python mainscript.py subscript arguments
I’ve figured out most of the details but I’m having a lot of trouble deciding on how to export an API (object or selected functions) to subscript
s that mainscript
imports. The intention is for the subscript
s to work as pluggable commands to mainscript
(in other words, there is no need for them to work stand-alone).
Things I’ve tried, that I think would be elegant enough are (after import subdirectory.subscript
in mainscript
):
-
import __main__
which works, but gives my subscript access to everything unconditionally and will likely be a source of horrible bugs if this is to be used by others.
-
from __main__ import *
which doesn’t work despite defining
__all__
to include the nameapi
at the end ofmainscript
(I just get told thatname 'api' is not defined
when I try to reference the object I want). -
from __main__ import api
which tells me
cannot import name api
.
So I’m at a position where, I either do the haphazard import __main__
which I don’t like at all, or have to move the api to a different file, which I also dislike because it would break the intended structure of:
mainscript.py
- subdirectory:
- subscript:
subscript.py
which, despite __init__.py
files that have to be everywhere along the chain, is relatively simple to work with. An api.py
somewhere would mean that, to maintain simplicity, I’d have to move mainscript.py
and api.py
into their own subdirectory and have a calling script where mainscript.py
used to be (a python script, to keep things easily cross-platform, but that just adds another script to the chain). I want to keep everything simple and obvious, which is why I’d prefer to have the simple api within the master caller script.
In summary: What is the recommended, if any, way to export an api object from a calling script to called scripts? Is this approach to exporting an api wrong?
Turn the API into a Python package and install it. Then it is out of your way, and the structure of the scripts’ directories can remain as it is.
1