0

Python 2 user here.

I am attempting to do a relative import within python subprocesses (i.e. processes called with python subprocess package https://docs.python.org/2/library/subprocess.html), which naturally fails with an "Attempted relative import in non-package." This is happening because the python script is getting executed as a main, and hence relative imports fail. I was wondering if there was a way around this?

Here is the file structure:

PythonProgramDriver/ subprocess1/ /helpers1 /script1 subprocess2/ /helpers2 /script2 data/

script2 needs to call a function in helpers1. But it cannot import the function. I have tried 'from .subprocess1 import helpers1' but I get the "Attempted relative import.." error......

Any help on this? Thanks

Tuomas Talvitie
  • 165
  • 2
  • 10
  • 1
    You can try running the script with `python -m script.py`, but the best fix would likely be to restructure your project so that you don't have to do the imports like that in the first place. – b_c Nov 12 '19 at 21:06
  • so I could open it as a subprocess but with the -m flag? What are some good resources for how to best structure python projects with multiple child processes? Thanks! – Tuomas Talvitie Nov 13 '19 at 16:12
  • To your first question: yes. For the rest, It all really depends on your specific needs. There's always the [`sys.path` hack](https://stackoverflow.com/a/7506029/4739755) - although discouraged, it can work as an ultimate fallback. Recommended design is to only execute top-level scripts, while the deeper stuff is imported around as necessary. If you need to do the subprocess route, the `python -m` approach is probably best, but maybe look into switching to threaded/multi-processed calls of imported functions. – b_c Nov 13 '19 at 16:41

0 Answers0