使用 java.lang.Runtime.getRuntime 在 matlab 中调用 python 脚本的多个实例不起作用

Calling multiple instances of python scripts in matlab using java.lang.Runtime.getRuntime not working

我在 windows 10 上 运行ning Matlab2017。 我调用了一个 python 脚本,它 运行 在云上执行一些语音识别任务,如下所示:

 userAuthCode=1;% authentication code for user account to be run on cloud
 cmd = ['C:\Python27\python.exe runASR.py userAuthCode];  
 system(cmd);

当调用上述命令时,python脚本运行是ASR云引擎上的输入音频文件,并且运行s,我可以看到语音识别来自 Python 的音频文件在 Matlab 控制台中的分数。 我想执行以下操作:

(1) 并行执行多个这样的命令。比方说,我有 2 个输入音频文件(每个都有不同的音频段),我想 运行 上面的命令 2 次,但是并行地,使用单独的进程。我能够创建一个应该能够执行此操作的代码片段:

 for i=1: 2
     userAuthCode=i;
     cmd = ['C:\Python27\python.exe runASR.py userAuthCode];  
     runtime = java.lang.Runtime.getRuntime();        
     pid(i) = runtime.exec(cmd);
 end

 for i=1:2
    pid(i).waitFor();
    % get exit status
    rc(i) = pid(i).exitValue();       
 end

现在,当执行上述代码时,我可以看到数据 1 的 ASRE 分数,但看不到数据 2 的分数。
变量 rc 中的退出状态是 0,1,,这证实了这一点。 问题是我不知道错误的原因,因为没有打印任何内容 Matlab。如何从 java/Matlab 中捕获的 Python 获取错误消息 变量,以便我看一下?

问题可能是多次调用 并行 ASRE(当然使用不同的用户帐户)可能不会 得到支持,但我不知道,除非我能看到错误。

(2) 当我 运行 一个单独的命令时,如 post 开头所述,我能够看到在 Matlab 控制台中打印的每个音频片段的乐谱消息,因为它们是从 Python 获得的。但是,使用 java.lang.Runtime.getRuntime() 和相关代码进行多处理时,Matlab 控制台中不会出现任何消​​息。有没有办法显示这些消息(我假设显示可能是异步的?)

谢谢
塞迪

一种方法是在 Python 中使用多处理。结果和任何错误消息都可以在列表中返回。

示例:

假设您有三个音频文件,your_function 将同时 运行 3 次并返回错误消息。

import subprocess
from multiprocessing import Pool, cpu_count

def multi_processor(function_name):

    # Use a regex to make a list of full paths for audio files in /some/directory
    # You could also just pass in a list of audio files as a parameter to this function
    file_list = []
    file_list = str(subprocess.check_output("find ./some/directory -type f -iname \"*a_string_in_your_aud_file_name*\" ",shell=True)).split('\n')
    file_list = sorted(file_list)

    # Test, comment out two lines above and put 3 strings in the list so your_function should run three times with 3 processors in parallel
    file_list.append("test1")
    file_list.append("test2")
    file_list.append("test3")

    # Use max number of system processors - 1
    pool = Pool(processes=cpu_count()-1)
    pool.daemon = True

    results = {}
    # for every audio file in the file list, start a new process
    for aud_file in file_list:
        results[aud_file] = pool.apply_async(your_function, args=("arg1", "arg2"))

    # Wait for all processes to finish before proceeding
    pool.close()
    pool.join()

    # Results and any errors are returned
    return {your_function: result.get() for your_function, result in results.items()}


def your_function(arg1, arg2):
    try:
        print("put your stuff in this function")
        your_results = ""
        return your_results
    except Exception as e:
        return str(e)


if __name__ == "__main__":
    multi_processor("your_function")