0

There is a python script start_test.py.

There is a second python script siple_test.py.

# pseudo code:
start_test.py --calls--> subprocess(python.exe simple_test.py, args_simple_test[])

The python interpreter for both scripts is the same. So instead of opening a new instance, I want to run simple_test.py directly from start_test.py. I need to preserve the sys.args environment. A nice to have would be to actually enter following code section in simple_test.py:

# file: simple_test.py
if __name__ == '__main__':
    some_test_function()

Most important is, that the way should be a universal one, not depending on the content of the simple_test.py.

This setup would provide two benefits:

  1. The call is much less resource intensive
  2. The whole stack of simple_test.py can be debugged with pycharm

So, how do I execute the call of a python script, from a python script, without starting a new subprocess?

Cutton Eye
  • 3,207
  • 3
  • 20
  • 39
  • You could import the function like this: `from file import function` see here: https://stackoverflow.com/questions/20309456/call-a-function-from-another-file-in-python – Mario Dec 16 '19 at 11:40
  • thx, but how do I preserve the individual context of the subprocess args? Just like sys.args = ['my', 'awesome','test','args']. Or is there a more pythonc way of doing it? – Cutton Eye Dec 16 '19 at 11:51

1 Answers1

1

"Executing a script" is a somewhat blurry term.

Typically the if __name__== "__main__": part does the argument (sys.argv) decoding and then calls a worker function with explicit parameters. For clarity: It should not do anything else, since this additional work can't be called without creating a new process causing all the overhead you are trying to avoid.

You simply bypass that and call this implementing routine directly.

So you end up with start_test.py containing something like:

from simple_test import worker
# ...
worker(typed_arg1, typed_arg2)
guidot
  • 5,095
  • 2
  • 25
  • 37