从同一上下文中的 python 脚本调用 python 脚本 [英] Call a python script from a python script within the same context

查看:43
本文介绍了从同一上下文中的 python 脚本调用 python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个python脚本start_test.py.

There is a python script start_test.py.

还有第二个 python 脚本 siple_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[])

两个脚本的 python 解释器是相同的.因此,我不想打开一个新实例,而是想直接从 start_test.py 运行 simple_test.py.我需要保留 sys.args 环境.很高兴实际上是在 simple_test.py 中输入以下代码部分:

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()

最重要的是,方式应该是通用的,而不是依赖于simple_test.py的内容.

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

这种设置将提供两个好处:

  1. 调用所需的资源要少得多
  2. simple_test.py的整个栈都可以用pycharm调试
  1. The call is much less resource intensive
  2. The whole stack of simple_test.py can be debugged with pycharm

那么,如何在不启动新子进程的情况下从 python 脚本执行 python 脚本的调用?

推荐答案

执行脚本"是一个有点模糊的术语.

"Executing a script" is a somewhat blurry term.

通常 if __name__== "__main__": 部分执行参数 (sys.argv) 解码,然后使用显式参数调用辅助函数.为清楚起见:它不应该做任何其他事情,因为在不创建新进程的情况下无法调用此额外工作,从而导致您试图避免的所有开销.

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.

所以你最终得到了包含如下内容的 start_test.py:

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

from simple_test import worker
# ...
worker(typed_arg1, typed_arg2)

这篇关于从同一上下文中的 python 脚本调用 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆