Greetings, I have a file which I connect to a db (MySQL) this file receives as a parameter a number of 13 digits (ruc) it receives well, but the problem arises when returning the response from JAVA to Python in python it receives as Str and not like Array .
Code of how I invoke the jar from Python:
import shlex, subprocess
import json
PARAMETRO = "1804464194001"
JAVA_CMD = 'java'
JAR_PATH = "catastro.jar"
command = [
JAVA_CMD,
'-jar',
JAR_PATH,
PARAMETRO
]
p = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
#shell=True
)
result = p.communicate()[0]
print(type(result))
The java code:
ArrayList<String> result = new ArrayList<String>();
....
try {
PreparedStatement st = conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()) {
//data resultset
String razonSocial = rs.getString("RAZON_SOCIAL");
String nombreComercial = rs.getString("NOMBRE_COMERCIAL");
String estadoContribuyente = rs.getString("ESTADO_CONTRIBUYENTE");
String obligado = rs.getString("OBLIGADO");
String tipoContribuyente = rs.getString("TIPO_CONTRIBUYENTE");
String calle = rs.getString("CALLE");
String numero = rs.getString("NUMERO");
String interseccion = rs.getString("INTERSECCION");
//data ArrayList
result.add(razonSocial);
result.add(nombreComercial);
result.add(estadoContribuyente);
result.add(obligado);
result.add(tipoContribuyente);
result.add(calle);
result.add(numero);
result.add(interseccion);
//return result
System.out.println(result);
}
conn.close();
rs.close();
st.close();
} catch(SQLException e) {
e.printStackTrace();
}
what returns from java:
['DIEGO ALBERTO AVILA', '', 'ACTIVO', 'N', 'OTRO', 'CEVALLOS', 'S/N','MOLINA']
So in theory it should be an array and for this I try to access it like this:
print(result[0])
Same as showing me:
[
Thanks for any suggestion..!!
thank you all for your comments after reading several blogs and comments I found the following way:
Result:
Of course there are others like:
Method 1
Result:
Method 2:
Result:
It is worth mentioning that these methods did not work for me except the first one that I placed.
I hope it helps someone and thanks for your suggestions..!!
Return data from Java
Actually, your Java program does not return an Array (as the title of your question indicates), but prints it to its standard output. From the moment you print it, it obviously becomes a string.
To actually return the array (via a
return
) would imply that you could somehow from Python load the Java class, call its method, and get the return value inlist
python form instead of Array java. This is generally very complex. It can be greatly simplified if instead of the interpreterpython
you use another calljython
to execute your program, since this interpreter is written in Java and can interact with other java classes natively.However, using Jython seems excessive to me for a case as simple as this, but it could be a good solution if the Java method returned something more complex, like an instance of a class with its data and its methods, perhaps containing references to others. objects etc
Serialization
The problem of converting a more or less complex data structure into a sequence of bytes is generally called serialization . A particular case is when you want to convert it to text, because in the end a string is nothing more than a sequence of bytes.
By printing the Array from Java you have solved the serialization problem in a very simple way, since Java contains methods to display the list in a serialized way without having to iterate through the elements. This method will also work if within the list its elements were other lists, since it would serialize them recursively.
To read that text from python and convert it back to the original data structure (a list) you have the reverse problem, called deserialization .
The solution you propose based on ignoring the brackets that surround the textual representation of the list, and then splitting its elements by commas, works for you in this case, but it is generally very fragile. What if the elements of the list were strings, and some of these strings contained commas? What if the elements of the list were other lists? What if they were another type of data such as a
Map<k,v>
?I think the most general, yet simple, solution is to use JSON as an intermediate representation. Namely:
System.println(gson.toJson(result);
json.loads()
In this very simple case, you can save the
Gson
in the Java part, since it will give the same result as theSystem.println()
direct one that you have tried, but in more complicated cases (elements that are strings, or sublists, or dictionaries) this solution will be much more generic.I found on StackOverflow that there is a fair module for converting an object-like str to the proper Python object, and it's safer than a simple
eval
, because it throws an exception when the result is not a valid Python data type: