Java程序中调用python程序

  1. 准备好一个Java程序 和 python 程序,确保在本机环境下能正常运行
    • 如图所示:
    • 在Java程序中调用python程序
      • import java.io.BufferedReader;
        import java.io.InputStreamReader;
         
         public class Program { 
        	
        	public static void main(String[] args){
        	
        		System.out.println("这是我的Java程序");
        		String url="E:\\desk\\test\\test.py";
        		String[] args1 = new String[]{"python ", url};
        		try{ 
        			Process pr=Runtime.getRuntime().exec(args1);
        			BufferedReader in = new BufferedReader(new InputStreamReader(
                            pr.getInputStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
        				System.out.println(line);
                    }
        			in.close();
        			pr.waitFor();
        		}catch(Exception e){
        			e.printStackTrace();
        		}
        	}
        }
        

        这个程序可以调用指定url路径下的python程序,可放在classpath:下给工程提供访问路径,也可以在部署服务器时,指定XXX.py的绝对路径。运行结果展示:

2.接下来讲,Java程序调用python程序,并传递参数给python程序,使该参数能参与python程序的运行:

  • python:test.py准备
import sys

arg1 = sys.argv[1]

print("这是我的python文件")
print("我的参数1:" + arg1)

  • Java:Program.java准备
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
     
     public class Program { 
    	
    	public static void main(String[] args){
    	
    		System.out.println("这是我的Java程序");
    		String url="E:\\desk\\test\\test.py";
    		String name = "namesocool";	//传递参数
    		String[] args1 = new String[]{"python ", url, name};
    		try{ 
    			Process pr=Runtime.getRuntime().exec(args1);
    			BufferedReader in = new BufferedReader(new InputStreamReader(
                        pr.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
    				System.out.println(line);
                }
    			in.close();
    			pr.waitFor();
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    

     

  • 展示效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值