问题描述
我正在从Java代码中调用Python脚本.这是代码:
I am calling a Python script from my Java code. This is the code :
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代码.
So, I am at a critical stage where I have a deadline for my startup and I have to show my MVP project to the client and I was thinking of calling Python script like this. It works when I am printing anything without dB connection and MySQLdb library. But when I include them, it does not run the python script. Whats wrong here. Isnt it suppose to run the process handling all the inputs. I have MySQLdb installed and the script runs without the java code.
我知道这不是解决问题的最佳方法.但是要向客户展示一些东西,我需要工作.有什么建议吗?
I know this is not the best way to solve the issue. But to show something to the client I need this thing working. Any suggestions ?
推荐答案
因此,我发现问题出在我通过Java传递来运行python程序的参数上.
So, I discovered that the issue was with the arguments that I was passing in Java to run the python program.
第一个参数是-python 2.6,但它应该只是python而不是一些版本号,因为与MySQLdB和python存在兼容性问题.
The first argument was - python 2.6 but it should have rather been just python not some version number because there was compatibility issue with MySQLdB and python.
我最终决定使用MySQL Python连接器代替python代码中的MySQLdB.它像魅力一样工作,问题得到了解决!
I finally decided to use MySQL Python connector instead of MySQLdB in python code. It worked like charm and the problems got solved !
这篇关于从JAVA MySQLdb导入调用Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!