0

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 subscripts that mainscript imports. The intention is for the subscripts 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):

  1. 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.

  2. from __main__ import *

    which doesn't work despite defining __all__ to include the name api at the end of mainscript (I just get told that name 'api' is not defined when I try to reference the object I want).

  3. 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?

0

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.

| improve this answer | |
  • but that's exactly what I wanted to avoid: having to turn the API into a package. It turns out my ordering in the main file was backwards and I fixed it. I left the question open to see if there's a different standard approach to doing this but it seems there isn't (further searching didn't reveal anything). I'm unsure if I should delete the question - I'm accepting this answer just to close the issue, but I must state that it is the solution I wanted to avoid. Regardless, my original design seems to work now. – mechalynx Oct 23 '14 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.