2
我从Java代码中调用Python脚本。这是代码:从JAVA调用Python脚本MySQLdb导入
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class JavaRunCommand { public static void main(String args[]) throws IOException { // set up the command and parameter String pythonScriptPath = "my-path"; String[] cmd = new String[2]; cmd[0] = "python2.6"; cmd[1] = pythonScriptPath; // create runtime to execute external command Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); // retrieve output from python script BufferedReader bfr = new BufferedReader(new InputStreamReader( pr.getInputStream())); String line = ""; while ((line = bfr.readLine()) != null) { // display each output line form python script System.out.println(line); } } }
python.py其中工程
import os from stat import * c = 5 print c
python.py不工作
import MySQLdb import os from stat import * c = 5 print c # some database code down
所以,我在一个关键阶段我的创业期限已到,我必须向客户展示我的MVP项目,并且我正在考虑调用Python脚本秒。它适用于打印没有dB连接和MySQLdb库的任何东西。但是当我包含它们时,它不会运行python脚本。这里有什么问题。它不是假设运行处理所有输入的过程。我安装了MySQLdb,脚本运行时没有Java代码。
我知道这不是解决问题的最佳方法。但为了向客户展示我需要这件事情。有什么建议么 ?
你有什么错误吗?如果你不打印数据库连接,你的java程序的输出是什么? – Nilesh 2013-03-07 06:05:24
您的python脚本是否从java以外的命令行运行?可能在命令shell中的Python无法找到该库。看看这个问题:http://stackoverflow.com/questions/135035/python-library-path并从java和独立打印sys.path – GregHNZ 2013-03-07 08:09:29