How to execute if statement using Jython - java

import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1:");
interp.exec(" print('in if statement!'");
}
}
I need to be able to execute Python code from a Java program, so decided to try out Jython, but I'm unfamiliar with it. I tried executing the above code, but got the error: "Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))". Any ideas what this means or how I can otherwise execute an if statement using the PythonInterpreter?

Conditionals must be entered as a single string and you have an extra parenthesis:
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1: print 'in if statement!'");
}
}

Rather than executing a script line by line with strings you can invoke the interpreter to run a file. All you have to do is provide a file path to your python file, in this example place script.py in the src folder.
script.py
if 2 > 1:
print 'in if statement'
JythonTest.java
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("src/script.py");
}
}

Related

Java new ProcessBuilder("gcc", "--version").start() does not print out results [duplicate]

This question already has answers here:
Run cmd commands through Java
(14 answers)
Closed 10 months ago.
I want to run some commands from Java, but the following program does not print out the expected result. Any ideas?
import java.io.IOException;
public class MyClass {
public static void main(String args[]) throws IOException {
Process p = new ProcessBuilder("gcc", "--version").start();
}
}
You need to set the source and destination for subprocess standard I/O to be the same as those of the current Java process. You can to this by calling:
ProcessBuilder.inheritIO();
So your example should look something like:
import java.io.IOException;
public class MyClass {
public static void main(String args[]) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("gcc", "--version");
processBuilder.inheritIO();
processBuilder.start()
}
}
For advanced process I/O usage you should take a look at ProcessBuilder and Process JavaDocs.

Maintain java object state when calling java process from bash script

public class Go {
private static SomeObject fld;
public static void main(String[] args) {
//depending on the args I do call different methods(among
//them one arg will do the job of initialization of fld variable)
}
}
I call the above java function from the bash script.
while true
do
read commands
java -cp some-jar.jar Go <commands>
then
Say command1 does initialization of fld in the Go class and command2 does some processing over the initialized field.
As I am calling different java processes for the different commands the objects fld state is not getting persisted for the next command.
How can I modify the code such that the fld information gets persisted for the next commands without using some database or deserializing and serializing?
You could store result in bash variable:
Go.java:
class Go {
private static String fld;
public static void main(String[] args) {
fld = args[0];
fld += fld.length();
System.out.println(fld);
}
}
run.sh
VALUE=test
while true
do
VALUE=`java Go $VALUE`
echo $VALUE
done
Output:
test4
test45
test456
test4567
test45678
Or store result into file, read it in bash and pass as parameter into Go.java .
Here is file storage example:
File example Go.java:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
class Go {
private static String fld;
public static void main(String[] args) throws IOException {
fld = args[0];
fld += fld.length();
FileWriter fileWriter = new FileWriter("store.txt");
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(fld);
printWriter.close();
}
}
File example run.sh:
VALUE=store
while true
do
java Go $VALUE
VALUE=`cat ./store.txt`
echo $VALUE
done
File example Output:
store5
store56
store567
store5678

Where does Java save files to?

I ran the below code and created a file. Where can I find it in my filesystem?
import java.io.*;
public class FileReaderDemo {
public static void main(String args[]) throws Exception {
File f = new File ("wayback.txt");
f.createNewFile();
System.out.println(f.exists());
}
}
Add the following to your program, run it and it'll show you the expected location:
System.out.println(f.getCanonicalFile());

How to pipe input from a Java program to another using Bourne Shell

I have two simple Java programs and I want to pipe the result of the "Test" to the "Test2".
public class Test{
public static void main(String args[]){
System.out.println("Hello from Test");
}
}
and
public class Test2{
public static void main(String args[]){
System.out.printf("Program Test piped me \"%s\"",args[0]);
}
}
After I compiled both of .java files I tried to run the pipe command from terminal
java Test | java Test2, but I get an ArrayIndexOutOfBoundsException which means that the args array is not initialized?
How can the Test2 application take the outputstream value that Test.main() produced through piping?
One way is to use xargs:
java Test| xargs -I ARGS java Test2 ARGS
Pipes connect one program’s standard output to another program’s standard input, not to the other program’s command-line arguments.
The second class will not get the piped output as arguments to its main method; it will get the piped output as its standard input. So you want to read the information from System.in:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Test2 {
public static void main(String args[])
throws IOException {
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
stdin.lines().forEachOrdered(
line -> String.format("Program Test piped me \"%s\"", line));
}
}

how to remove this error "*sys-package-mgr* " and how to run python file into following case :

i have a scenario such as below:
pyhton file name is sir_desc.py placed into this path "E:/Program Files/Java/jdk1.8.0_92/bin/sir_desc.py"
jython-2.5 jar file placed into ext folder of java dierectory
i able to run python code by using these command from commandprompt :
C:\Python27>python
import sir_desc
sir_desc.get_url_text("http://www.tutorialspoint.com/java/")
steps to run python file
python code run successfully and return text as output
how to run python file from following java code and how i remove "sys-package-mgr : can't create package cashe dir" ??
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class method {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("E:/Program Files/Java/jdk1.8.0_92/bin/sir_desc.py");
PyObject str = interpreter.eval("repr(get_url_text(\"http://www.tutorialspoint.com/java/\"))");
System.out.println(str.toString());
}
}

Categories

Resources