java运行python脚本_如何从Java执行Python脚本?

在Java中尝试执行Linux命令如ls或pwd没有问题,但无法成功运行Python脚本。问题在于尝试使用Runtime.getRuntime().exec()直接包含管道操作符(|),这是不正确的。解决方案包括创建一个shell脚本来执行命令或者将命令作为字符串数组传递给exec()方法,确保正确处理管道和可能需要的root权限。同时,脚本可能需要参数,这需要正确地在命令中包含。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.

This is my code:

Process p;

try{

System.out.println("SEND");

String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";

//System.out.println(cmd);

p = Runtime.getRuntime().exec(cmd);

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String s = br.readLine();

System.out.println(s);

System.out.println("Sent");

p.waitFor();

p.destroy();

} catch (Exception e) {}

Nothing happened. It reached SEND but it just stopped after it...

I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).

解决方案

You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.

You could do either

Put your command to a shell script and execute that shell script with .exec() or

You can do something similar to the following

String[] cmd = {

"/bin/bash",

"-c",

"echo password | python script.py '" + packet.toString() + "'"

};

Runtime.getRuntime().exec(cmd);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值