Runtime.getRuntime().exec实现Java调用python程序

12 篇文章 0 订阅

在使用jython实现Java调用python程序,如果python程序中包含有第三方库(如numpy),则会报如下错误:

Exception in thread "main" Traceback (innermost last):
  File "pyfile/detect.py", line 3, in ?
ImportError: no module named numpy

推荐使用的方法是使用Runtime.getRuntime().exec()来实现Java调用python,调用代码如下所示:

package com.xiaoxian.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test2 {

	public static void main(String[] args) throws IOException, InterruptedException {
		System.out.println("start python");
		//需传入的参数
		String a = "aaa", b = "bbb", c = "cccc", d = "dddd";
		//设置命令行传入的参数
//		String[] arg = new String[]{"python", "pyfile/test2.py", a, b, c, d};
		String[] arg = new String[]{"python", "pyfile/detect.py"};
		Process pr = Runtime.getRuntime().exec(arg);
		
		BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));  
        String line;  

        while ((line = in.readLine()) != null) {  
//            line = decodeUnicode(line);  
            System.out.println(line);  
        }  
        in.close();  
		System.out.println("end");
		pr.waitFor();
	}
}

其中

<strong>String[] arg = new String[]{"python", "pyfile/test2.py", a, b, c, d};</strong>

可用于设置传入python程序的参数。

 

 

两个注意事项:一、python程序中不能含有中文;

 

 

                        二、python使用的文件路径最好使用绝对路径;

 

 

 

欢迎关注我的公众号:

编程技术与生活(ID:hw_cchang)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
利用多进程,调用DOS命令查看网络信息 public class ipconfig extends JFrame{ static TextField ip_text=new TextField(15); static TextField mac_text=new TextField(15); static TextField subnetmask_text=new TextField(15); static TextField gateway_text=new TextField(15); static TextField dns_text=new TextField(15); static JPanel subnetmask=new JPanel(new FlowLayout()); static JPanel gateway=new JPanel(new FlowLayout()); static JPanel IP=new JPanel(new FlowLayout()); static JPanel dns=new JPanel(new FlowLayout()); public static void main(String[] args) throws UnknownHostException { ipconfig f=new ipconfig(); f.setTitle("查看本机网络设置QQ125004485"); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocation(400,400); f.setSize(new Dimension(200,300)); // gotoUrlWindows("http://ygsn.taobao.com/"); //gotoUrlWindows("www.sohu.com"); f.setResizable(false); f.setLayout(new GridLayout(6,1)); //IP文本框 setCFont(IP); IP.add(new Label("IP:")); IP.add(ip_text); ip_text.setText(getLocalIp()); //MAC 文本框 JPanel MAC=new JPanel(new FlowLayout()); setCFont(MAC); MAC.add(new Label("MAC:")); MAC.add(mac_text); mac_text.setText(getMacAddressIP(ip_text.getText())); //子网掩码 setCFont(subnetmask); subnetmask.add(new Label("子网掩码:")); subnetmask.add(subnetmask_text); subnetmask_text.setText(getSubnetMask()); //网关 setCFont(gateway); gateway.add(new Label("网关:")); gateway.add(gateway_text); gateway_text.setText(getGateWay()); //DNS setCFont(dns); dns.add(new Label("DNS:")); dns.add(dns_text); dns_text.setText(getDns()); //加载文本框 f.add(subnetmask); f.add(MAC); f.add(IP); f.add(gateway); f.add(dns); f.pack(); } // Windows platform goto url private static void gotoUrlWindows(String url){ String cmd = "rundll32 url.dll,FileProtocolHandler " + url; try { Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } } //取IP private static String getLocalIp() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress(); } //设置字体 private static void setCFont(Container c) { c.setFont(new Font( "宋体 ",Font.BOLD,15)); } public static String getMacAddressIP(String remotePcIP) { String str = ""; String macAddress = ""; try { Process pp = Runtime.getRuntime().exec("nbtstat -A " + remotePcIP); InputStreamReader ir = new InputStreamReader(pp.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.indexOf("MAC Address") > 1) { macAddress = str.substring( str.indexOf("MAC Address") + 14, str.length()); break; } } } } catch (IOException ex) { } return macAddress; } public static String getSubnetMask() { String str = ""; String subnetmask = ""; try { Process pp = Runtime.getRuntime().exec("ipconfig /all"); InputStreamReader ir = new InputStreamReader(pp.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.indexOf("Subnet Mask") > -1) { subnetmask = str.substring( str.indexOf("Subnet Mask") + 36, str.length()); break; } } } } catch (IOException ex) { } return subnetmask; } public static String getGateWay() { String str = ""; String gateway = ""; try { Process pp = Runtime.getRuntime().exec("ipconfig /all"); InputStreamReader ir = new InputStreamReader(pp.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.indexOf("Default Gateway") > -1) { gateway = str.substring( str.indexOf("Default Gateway") + 36, str.length()); break; } } } } catch (IOException ex) { } return gateway; } public static String getDns() { String str = ""; String dns = ""; try { Process pp = Runtime.getRuntime().exec("ipconfig /all"); InputStreamReader ir = new InputStreamReader(pp.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.indexOf("DNS Servers") > -1) { dns = str.substring( str.indexOf("DNS Servers") + 36, str.length()); break; } } } } catch (IOException ex) { } return dns; } }
引用提到了Runtime.getRuntime().exec()方法,该方法可以在Android中执行命令或创建进程。根据引用,您可以使用这种方法从Java代码中调用Python脚本。但需要注意的是,引用指出正确的写法应该是Runtime.getRuntime()而不是getruntime。因此,根据您的问题"android8 Runtime.getRuntime().exec",您可以使用以下代码来执行命令或创建进程: ```java Runtime runtime = Runtime.getRuntime(); String command = "your_command_here"; try { Process process = runtime.exec(command); // 处理进程的输出或其他操作 } catch (IOException e) { e.printStackTrace(); } ``` 在上述代码中,将"your_command_here"替换为您要执行的具体命令。这样,您就可以在Android 8及以上版本中使用Runtime.getRuntime().exec()方法执行命令或创建进程了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [使用runtime.getruntime.execJava调用python脚本(Calling python script from Java using runtime....](https://blog.csdn.net/weixin_39618730/article/details/110567660)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [Android Runtime.getRuntime().exec()](https://blog.csdn.net/xianrenli38/article/details/117484708)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cchangcs

谢谢你的支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值