python - 从python中的单个脚本运行多个脚本

标签 python multithreading parallel-processing multiprocessing

我有两个脚本 Server.pyServerGUI.py。我希望它们独立并行运行。假设我制作了另一个脚本 ma​​in.py。如何从 ma​​in.py 运行 Server.pyServerGUI.py

你能给我推荐ma​​in.py的代码吗?

最佳答案

要从 python 脚本中运行 2 个或更多脚本,您可以使用带有 nohup 的子进程包。这将在后台运行每个脚本,允许您从同一源脚本并行运行它们。此外,作为一个选项,此示例会将每个脚本的标准输出保存在不同的文件中

import os
from subprocess import call
from subprocess import Popen


# subprocess.call(['python', 'exampleScripts.py', somescript_arg1, somescript_val1,...]).

Popen(['nohup', 'python', 'exampleScripts.py'],
                 stdout=open('null1', 'w'),
                 stderr=open('logfile.log', 'a'),
                 start_new_session=True )
                 
Popen(['nohup', 'python', 'exampleScripts.py'],
                 stdout=open('null2', 'w'),
                 stderr=open('logfile.log', 'a'),
                 start_new_session=True )

Popen(['nohup', 'python', 'exampleScripts.py'],
                 stdout=open('null3', 'w'),
                 stderr=open('logfile.log', 'a'),
                 start_new_session=True )      

输出:每个脚本的开始和结束时间重叠,显示第二个脚本在第一个脚本结束之前开始

(ds_tensorflow) C:\DataScience\SampleNotebooks\Threading>python RunScripts.py

(ds_tensorflow) C:\DataScience\SampleNotebooks\Threading>cat null*
2020-07-13 15:46:21.251606
List processing complete.
2020-07-13 15:46:29.130219
2020-07-13 15:46:22.501599
List processing complete.
2020-07-13 15:46:31.227954
2020-07-13 15:46:23.758498
List processing complete.
2020-07-13 15:46:32.431079

如果您想将代码保存在一个地方,您也可以对函数使用相同的想法。此示例将并行运行两个不同的函数两次。

函数示例:

...
import threading
...

def some_function()
    # code

def other_function()
    # code

if __name__ == "__main__":    
    jobs = []
    #same function run multiple times
    threads = 2
    for i in range(0, threads):
        out_list = list()
        thread1 = threading.Thread(target=some_function(size, i, out_list))
        jobs.append(thread1)
        thread2 = threading.Thread(target=other_function(size, i, out_list))
        jobs.append(thread2)
        
    # Start the threads (i.e. calculate the random number lists)
    for j in jobs:
        j.start()

    # Ensure all of the threads have finished
    for j in jobs:
        j.join()

    # continue processing

关于python - 从python中的单个脚本运行多个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62870725/

相关文章:

解压缩具有深层目录结构的存档时出现 Python IOError 异常

visual-studio - 在 Visual Studio 调试器中中断线程创建

haskell - 并行树搜索

c - Open MPI 的矩阵乘法错误

python - 从 PDF 文件中突出显示的注释中提取文本

python - 参数化 django 的迁移以跳过(--fake 以编程方式)

python - 无法导入Python包

c++ - 在 librdkafka 中,dr_cb 在 produce() 线程或 poll() 线程上执行

java - 为什么这个片段抛出 NullPointerException

r - 在 R 中进行并行处理时是否应该使用每个核心?