从Java Process运行交互式Python GUI(Matplotlib)

时间:2017-06-30 13:36:04

标签: java python matplotlib processbuilder runtime.exec

我对此做了很多研究,遗憾的是我找不到适合我目前所遇问题的答案。

我的问题并不像"我如何从Java运行python脚本,"至少有10个线程都包含相同的答案。我明白该怎么做。我的问题如下:

我有一个.py文件(gui.py),看起来像这样:

#!/usr/bin/env python
import matplotlib.pyplot as plt
import copy
import math
import numpy as np

class GUI(object):
    ...
    ...
    ...
if __name__ == '__main__':
    GUI.run()

这个gui是一个交互式matplotlib图,用户可以在其中绘制内容。细节并不重要 - 只要matplotlib窗口打开,底线就是脚本运行。

现在,我正在构建一个Java应用程序,并且有一个按钮,单击该按钮会创建一个将调用该脚本的Java Process对象。我从阅读其他帖子中了解到,无法从Java运行时调用PIPE,因此我创建了一个包含此python脚本的.sh文件。

shell.sh

#!/bin/sh
python /mypath/to/the/gui.py

调用shell脚本的Java:

view.getLaunchGuiButton().addActionListener((e) -> {

            try {
                String[] prcArgs = new String[] { "/mypath/to/shell.sh" };
                Process proc = Runtime.getRuntime().exec(prcArgs);

            } catch (IOException e1 ) {
                e1.printStackTrace();
            }
        });

shell脚本是正确的 - 当我从终端正确运行它时,一切正常。

我知道Java确实正在执行shell脚本,并调用python脚本。没有错误。我没有设置任何BufferedReader,因为没有什么可读的 - 我只需要GUI打开。我相信问题是,一旦shell被执行,"终端"由Runtime打开的所谓说话会立即关闭,因此它会杀死python脚本,从而杀死GUI。

我的问题是,如何让Runtime简单地运行并立即终止python脚本(AKA关闭终端)?

我已经完成的事情:

  • chmod +x ../../shell.sh
  • 在shell脚本中使用nohup /call/python/here &尝试。没有工作。
  • 尝试使用Java ProcessBuilder代替Runtime。没有区别。

有什么想法吗?提前谢谢大家。

1 个答案:

答案 0 :(得分:1)

  1. 从Java Button listner我执行xterm:

    try {
            Process p = Runtime.getRuntime().exec("xterm");
            Thread.sleep(1500);
    
        } catch (IOException e1 ) {
            e1.printStackTrace();
        }
    
  2. ~/.bashrc中,我添加了使用GUI启动Python脚本的命令:

    if [[ -z "$XTERM_ONCE" ]]
    then
        export XTERM_ONCE=$(date)
        cd  /home/qswadey/path/to/py/script/
        python3 pyscript_with_GUI.py
    fi
    

    Python GUI显示并继续......

  3. 对于所有xterm,在xterm启动时运行命令的想法来自此线程:How to run a command on the startup of an xterm?

    Thread.sleep仅用于保持xterm一段时间以查看短命令的输出,但xterm仍然以交互模式运行

相关问题