解决python的jpype包出现的“jvm already started”

描述:

      使用flask启动一个web服务,其中有个功能需要调用jar包来得到结果,但是开启服务后,第一次成功调用,但是第二次就会出现jvm already started。


解决方法:

    使用多进程,另起一个进程来加载jar包,在得到想要的结果后杀掉进程

demo:

# 加载jar包
def demo(q, data):
    jarpath = os.path.join(os.getcwd(), "info\\ner\c111.jar")
    jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)
    Test = jpype.JClass('cetc28.eventdetection.entity_extraction.Ner')
    res = Test.nerSentence(data)
    q.put(res)
@index_blu.route('/question')
def question():
    """在视图中使用多进程调用demo函数"""
    data = request.args.get('val')
    q = multiprocessing.Queue()
    p = multiprocessing.Process(target=java_loop, args=[q, data])
    p.daemon = True
    p.start()
    a = q.get()
    p.terminate()

    return a


     成功解决问题

有更好的办法欢迎在评论留言,谢谢

猜你喜欢

转载自blog.csdn.net/xiaoliu_alone/article/details/85678601
今日推荐