Call a python script from a python script within the same context

旧城冷巷雨未停 提交于 2020-01-25 10:21:51

问题


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?


回答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)


来源:https://stackoverflow.com/questions/59355847/call-a-python-script-from-a-python-script-within-the-same-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!