Java调用Python脚本

简介: Java调用Python脚本

1. 通过Runtime进行调用

  • 传参
/**
    * 通过Runtime调用Python脚本
    * @param args
    * @throws IOException 
    * @throws InterruptedException 
    */
   public static void main(String[] args) throws IOException, InterruptedException{
       String exe = "python3";
       String command = "D:\\calculator_simple.py";
       String[] cmdArr = new String[] {exe, command, "1", "2"};
       Process process = Runtime.getRuntime().exec(cmdArr);
       InputStream is = process.getInputStream();
       DataInputStream dis = new DataInputStream(is);
       String str = dis.readLine();
       process.waitFor();
       System.out.println(str);
   }
  • 返回结果
public static void main(String[] args) throws IOException, InterruptedException{
   String python = "python3.10"; 
   String script = "D:\\calculator_simple.py";
   String command = python + " " + script + " 1 2";
   Process process = Runtime.getRuntime().exec(command); 
   BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
   String line;
   String result = null;
   while ((line = in.readLine()) != null) {
       result = line;
       System.out.println("返回结果:" + result);
   }
   in.close();
   process.waitFor();
   System.out.println(result);
}
  • calculator_simple.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# from sys import argv
import sys
num1=sys.argv[1]
num2=sys.argv[2]
# 结果
sum = int(num1) + int(num2)
print(sum)

通过Runtime调用Python程序与直接执行Python程序的效果是一样的,可以在Python中读取传递的参数,也可以在Java中读取到Python的执行结果

2. 通过Jython调用

Jython是Python语言在Java平台的实现

<!--<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython</artifactId>
    <version>2.7.0</version>
</dependency>-->
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.2</version>
</dependency>
  • 执行python语句
@Test
void executePython() {
    // python语句,打印 Hello world !
    String py = "print('Hello world!')";
    PythonInterpreter interpreter = new PythonInterpreter();
    // 执行 Python 语句
    interpreter.exec(py);
}
// 在Java中执行Python语句,相当于在Java中嵌入了Python程序
// 意义不大
public static void main(String[] args) {
    System.setProperty("python.home", "D:\\jython2.7.0");
    PythonInterpreter interp = new PythonInterpreter();
    // 执行Python程序语句
    interp.exec("import sys");
    interp.set("a", new PyInteger(42));
    interp.exec("print a");
    interp.exec("x = 2+2");
    PyObject x = interp.get("x");
    System.out.println("x: " + x);
}
  • 执行python脚本
@Test
void executePythonFile() {
    // 定义脚本路径
    String path = "D:\\test.py";
    PythonInterpreter interpreter = new PythonInterpreter();
    // 执行脚本文件
    interpreter.execfile(path);
}
  • test.py
print('hello world by file')
  • 动态传参
@Test
void executePythonFunction() {
    PythonInterpreter interpreter = new PythonInterpreter();
    // 指定指定路径下的 python 脚本
    interpreter.execfile("D:\\test.py");
    // 指定需要调用的函数
    PyFunction function = interpreter.get("sendEmail", PyFunction.class);
    // ↓↓↓↓↓↓↓↓ 需要传入的参数 ↓↓↓↓↓↓↓↓
    // 邮件接受者
    PyString receiver = Py.newStringOrUnicode("xxx@qq.com");
    // 邮件主题
    PyString subject = Py.newStringOrUnicode("打个招呼【动态参数】");
    // 邮件内容
    PyString content = Py.newStringOrUnicode("我是Micky哈【动态参数】");
    // 调用
    PyObject pyObject = function.__call__(receiver, subject, content);
    // 打印返回结果
    System.out.println(String.format("result: %s", pyObject));
}
  • test.py 发送邮件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
# 邮件服务器地址
mail_host = 'smtp.qq.com'
# 邮件服务器用户名
mail_user = 'xxx@qq.com'
# 邮件服务器登录密码(有些是授权码)
mail_pwd = 'xxx'
# 邮件发送者
sender = 'xxx@qq.com'
def sendEmail(receiver, subject, content):
    """
    发送邮件
    :param receiver: 接收者
    :param subject: 邮件主题
    :param content: 邮件内容
    :return:
    """
    message = MIMEText(content, 'plain', 'utf-8')
    # 邮件主题
    message['Subject'] = subject
    # 发送方
    message['From'] = sender
    # 接收方
    message['To'] = receiver
    try:
        # 连接到服务器
        smtp = smtplib.SMTP_SSL(mail_host)
        # 登录服务器
        smtp.login(mail_user, mail_pwd)
        # 发送
        smtp.sendmail(sender, receiver, message.as_string())
        # 推出
        smtp.quit()
        return 'send email success ...'
    except smtplib.SMTPException as e:
        print('error', e)
if __name__ == '__main__':
    # 邮件接受者
    receiver = 'xxx@qq.com'
    # 邮件主题
    subject = '打个招呼'
    # 邮件内容
    content = '我是Micky哈'
    sendEmail(receiver, subject, content)


相关文章
|
2天前
|
Python
用python转移小文件到指定目录并压缩,脚本封装
这篇文章介绍了如何使用Python脚本将大量小文件转移到指定目录,并在达到大约250MB时进行压缩。
14 2
|
8天前
|
运维 Prometheus 监控
自动化运维的魔法:使用Python脚本简化日常任务
【8月更文挑战第50天】在数字化时代的浪潮中,自动化运维成为提升效率、减少人为错误的利器。本文将通过一个实际案例,展示如何利用Python脚本实现自动化部署和监控,从而让运维工作变得更加轻松和高效。我们将一起探索代码的力量,解锁自动化运维的神秘面纱,让你的工作环境焕然一新。
127 81
|
1天前
|
Web App开发 存储 安全
Python编写脚本,打开浏览器输入网址,自动化登陆网站
Python编写脚本,打开浏览器输入网址,自动化登陆网站
10 4
|
3天前
|
运维 监控 Python
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第23天】在本文中,我们将探索如何通过编写Python脚本来自动化常见的系统管理任务,从而提升效率并减少人为错误。文章将介绍基础的Python编程概念、实用的库函数,以及如何将这些知识应用于创建有用的自动化工具。无论你是新手还是有经验的系统管理员,这篇文章都将为你提供有价值的见解和技巧,帮助你在日常工作中实现自动化。
|
5天前
|
运维 监控 安全
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第21天】在快速迭代的软件开发环境中,运维工作往往因为重复性高、易出错而被诟病。本文将介绍如何通过编写简单的Python脚本来自动化这些日常任务,从而提升效率和减少错误。我们将以实际案例为基础,展示如何从零开始构建一个自动化脚本,并解释其背后的原理。文章旨在启发读者思考如何利用编程技能来解决工作中的实际问题,进而探索技术与日常工作流程结合的可能性。
|
1天前
|
Python Windows
python之windows脚本启动bat
python之windows脚本启动bat
|
23天前
|
存储 Shell 区块链
怎么把Python脚本打包成可执行程序?
该文档介绍了如何将Python脚本及其运行环境打包成EXE可执行文件,以便在不具备Python环境的计算机上运行。首先确保Python脚本能够正常运行,然后通过安装PyInstaller并使用`--onefile`参数将脚本打包成独立的EXE文件。此外,还提供了去除命令行窗口和指定可执行文件图标的详细方法。这些步骤帮助用户轻松地将Python程序分发给最终用户。
怎么把Python脚本打包成可执行程序?
|
2天前
|
运维 监控 Python
自动化运维:使用Python脚本实现日常任务
【9月更文挑战第24天】在现代的软件开发周期中,运维工作扮演着至关重要的角色。本文将介绍如何利用Python编写简单的自动化脚本,来优化和简化日常的运维任务。从备份数据到系统监控,Python的易用性和强大的库支持使其成为自动化运维的首选工具。跟随这篇文章,你将学习如何使用Python编写自己的自动化脚本,提高运维效率,减少人为错误,并最终提升整个开发流程的质量。
|
11天前
|
机器学习/深度学习 人工智能 安全
python和Java的区别以及特性
Python:适合快速开发、易于维护、学习成本低、灵活高效。如果你需要快速上手,写脚本、数据处理、做点机器学习,Python就是你的首选。 Java:适合大型项目、企业级应用,性能要求较高的场景。它类型安全、跨平台能力强,而且有丰富的生态,适合更复杂和规模化的开发。
16 3
|
14天前
|
SQL JavaScript 前端开发
用Java、Python来开发Hive应用
用Java、Python来开发Hive应用
19 6