java调用python程序并传递参数

一、java调用python程序,返回字符串

  1. python脚本
def get_path(filename):
    y_t = np.loadtxt(filename)
    peolpex = int(y_t[0][0])
    peolpey = int(y_t[0][1])
    firex = int(y_t[1][0])
    firey = int(y_t[1][1])

    answer = getQ(peolpex, peolpey, firex, firey)
    return answer


if __name__ == "__main__":
    filename = sys.argv[1]
    # print(filename)

    # root = Tk()
    # canvas = Canvas(root, bg="white")
    # canvas.pack()
    # colors = ['red', 'orange',  'green', 'black','yellow','white','pink']

    result = get_path(filename)
    # with open(filename, 'w') as f:
    #     f.write(result)
    print result

上面脚本会print一个字符串;

  1. java调用程序
String result = "";

        try {
            Process process = Runtime.getRuntime().exec("python /home/jia/fireevacuation/my.py " + filename);
//            process.waitFor();
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            result = input.readLine();
            input.close();
            ir.close();
//            process.waitFor();
        } catch (IOException e) {
            logger.error("调用python脚本并读取结果时出错:" + e.getMessage());
        }
        return result;

此时会将python的结果作为一行返回,只需要readline一次;

二、 传递参数

  1. java调用传递参数
 String[] args=new String[]{"python","D:\\pyworkpeace\\9_30_1.py","name"};
 Process pr=Runtime.getRuntime().exec(args);

python表示python.exe;
D:\\pyworkpeace\\9_30_1.py表示执行脚本的路径;
name表示参数,可以为多个参数
  1. python程序接受参数
url = ''
if __name__ == '__main__':
    for i in range(1, len(sys.argv)):
        url = sys.argv[i]

其中需要注意的是接收参数从sys.argv[1]开始,sys.argv[0]是python脚本的参数地址,没什么用。

》》》博主长期更新学习心得,推荐点赞关注!!!
》》》若有错误之处,请在评论区留言,谢谢!!!

你可能感兴趣的:(java)