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?

2
  • You could import the function like this: from file import function see here: stackoverflow.com/questions/20309456/… Commented Dec 16, 2019 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? Commented Dec 16, 2019 at 11:51

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.