使用java.lang.Runtime.getRuntime无法在matlab中调用多个python脚本实例

问题描述 投票:6回答:1

我在Windows 10上运行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云引擎上运行输入音频文件,并且在运行时,我可以在Matlab控制台中看到来自Python的音频文件的语音识别分数。我想做以下事情:

(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

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

问题可能是并不支持多个并行呼叫(当然使用不同的用户帐户),但除非我能看到错误,否则我不会知道。

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

谢谢 sedy

java python matlab multiprocessing
1个回答
1
投票

一种方法是在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")
© www.soinside.com 2019 - 2024. All rights reserved.