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)