How to execute Python script from Java (via command line)?
You cannot use the PIPE inside the Runtime.getRuntime().exec()
as you do in your example. PIPE is part of the shell.
You could do either
- Put your command to a shell script and execute that shell script with
.exec()
or You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
Run python script through Java with files arguments
Unlike python Java may need some help. Do I guess correctly you are running on Windows?
You invoke the Runtime.exec() method. The method returns a Process instance, and in it's documentation you can read
By default, the created process does not have its own terminal or
console. All its standard I/O (i.e. stdin, stdout, stderr) operations
will be redirected to the parent process, where they can be accessed
via the streams obtained using the methods getOutputStream(),
getInputStream(), and getErrorStream(). The parent process uses these
streams to feed input to and get output from the process. Because some
native platforms only provide limited buffer size for standard input
and output streams, failure to promptly write the input stream or read
the output stream of the process may cause the process to block, or
even deadlock.
So it is likely your process is started by the OS but gets blocked due to I/O restrictions. Get around that by reading the STDOUT and STDERR streams until your process finishes. One good programming model is visible at https://www.baeldung.com/run-shell-command-in-java
How to call a Python script with arguments from Java class
Have you looked at these? They suggest different ways of doing this:
Call Python code from Java by passing parameters and results
How to call a python method from a java class?
In short one solution could be:
public void runPython()
{ //need to call myscript.py and also pass arg1 as its arguments.
//and also myscript.py path is in C:\Demo\myscript.py
String[] cmd = {
"python",
"C:/Demo/myscript.py",
this.arg1,
};
Runtime.getRuntime().exec(cmd);
}
edit: just make sure you change the variable name from str to something else, as noted by cdarke
Your python code (change str to something else, e.g. arg and specify a path for file):
def returnvalue(arg) :
if arg == "hi" :
return "yes"
return "no"
print("calling python function with parameters:")
print(sys.argv[1])
arg = sys.argv[1]
res = returnvalue(arg)
print(res)
with open("C:/path/to/where/you/want/file.txt", 'w') as target: # specify path or else it will be created where you run your java code
target.write(res)
Run Python script through Java with importing just once
You could communicate between java and Python with pipes.
You run your Python as you do now (without command line args)
Python script
you write an infinite loop in python that will
read data from the
standard input (it will be your arg for the function)You call your function
you write the answer to the standard output
Java
Write a method for sending args to python
write to the pipe the arg of your function
read the answer from the pipe
You're done.
Here is some snippet
Here how you create your tube
Process p = Runtime.getRuntime().exec(commande);
BufferedReader output = getOutput(p); //from python to java
BufferedReader error = getError(p); //from python to java
PrintWriter input = getInput(p); //from java to python
private static BufferedReader getOutput(Process p) {
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
private static BufferedReader getError(Process p) {
return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
private static PrintWriter getInput(Process p){
return new PrintWriter (new OutputStreamWriter(p.getOutputStream()));
}
Running a .py file from Java
You can use like this also:
String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );
or
String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
Run Python script from Java
Related Topics
Java.Lang.Classnotfoundexception: Didn't Find Class on Path: Dexpathlist
How to Return a Documentsnapshot as a Result of a Method
How to Set a Custom Font For Entire of Application
Should I Actually Remove the Valueeventlistener
Android 5.0 - Add Header/Footer to a Recyclerview
Where to Store Application Data (Non-User Specific) on Linux
Why Use Getters and Setters/Accessors
Convert a String Representation of a Hex Dump to a Byte Array Using Java
What Are the Possible Values of the Hibernate Hbm2Ddl.Auto Configuration and What Do They Do
Mocking Static Methods With Mockito
How to Simulate the C++ 'Friend' Concept in Java
Download a File With Android, and Showing the Progress in a Progressdialog
Firebase Android Listview Not Being Displayed
How to Ping External Ip from Java Android
How to Execute Python Script from Java (Via Command Line)
Difference Between Public, Protected, Package-Private and Private in Java