简体   繁体   English

Python:从同一个解释器中同时执行多个脚本

[英]Python: Execute multiple Scripts simultaneously from same Interpreter

I have a python script , which is executing again 4-5 python scripts . 我有一个python脚本 ,该脚本再次执行4-5个python脚本 For performance reasons i want to use same interpreter for executing all the script. 出于性能原因,我想使用相同的解释器执行所有脚本。

How could I handle this issue? 我该如何处理?

The obvious solution (which may require a little tweaking) is to just call the main function of each script from a master script. 显而易见的解决方案(可能需要进行一些调整)是仅从主脚本调用每个脚本的主要功能。 Eg, if script1.py contains: 例如,如果script1.py包含:

#!/usr/bin/python
def main():
  // Do something
if __name__ == "__main__":
   main()

put in master.py 放入master.py

#!/usr/bin/python
import script1
def main():
  script1.main()

if __name__ == "__main__":
  main()

You can continue this pattern for as many scripts as you want. 您可以根据需要继续对任意数量的脚本使用此模式。

Maybe you're looking for the execfile function in Python 2.x. 也许您正在寻找Python 2.x中的execfile函数。

In Python 3 it was removed, but there are simple alternatives . 在Python 3中已将其删除,但是有一些简单的替代方法

I wrote a package to execute multiple scripts from the same interpreter (sequentially not simultaneously). 我编写了一个程序包,以从同一个解释器执行多个脚本(顺序不同时执行)。

Installation : 安装方式

pip install mand

Usage : 用法

mand script1.py script2.py script3.py script4.py

You can specify module paths or module names. 您可以指定模块路径或模块名称。


You may be able to run scripts at the 'same time' on using the runpy stdlib module (for python3) and threading stdlib module. 您可以使用runpy stdlib模块(适用于python3)和线程化 stdlib模块,在“相同时间”运行脚本。 Where you call runpy.run_path or runpy.run_module in separate threads, but you will only see performance benefits if the modules are IO bound and not CPU bound. 在单独的线程中调用runpy.run_pathrunpy.run_module ,但是仅当模块受IO绑定而不受CPU绑定时,您才会看到性能优势。


Using multiprocessing or os.system will spawn separate interpreters for each script, so the modules wouldn't be running in the same interpreter. 使用multiprocessing或os.system将为每个脚本生成单独的解释器,因此这些模块不会在同一解释器中运行。

The currently executing interpreter is available in sys.executable . sys.executable提供了当前执行的解释器。 You can just pass that explicitly to subprocess.Popen as the first argument, or pass it as the 'executable' argument. 您可以将其显式传递给subprocess.Popen作为第一个参数,也可以将其作为“可执行”参数传递。

I don't think this is recommended, but worst case scenario you could make the system 'run' each script from within another: 我不建议这样做,但是在最坏的情况下,您可以使系统从另一个内部“运行”每个脚本:

import os
os.system('python script1.py')
os.system('python script2.py')
os.system('python script3.py')
os.system('python script4.py')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM