This question already has answers here:
Calling Java app with "subprocess" from Python and reading the Java app output
(2 answers)
Closed 8 years ago.
I am running a Python script that runs a Java class that requires nondeterministic user input:
import sys
import subprocess
from subprocess import Popen, PIPE
p = Popen("java myclass", shell=True, stdout=subprocess.PIPE)
while True:
inline = p.stdout.readline()
if not inline:
break
sys.stdout.write(inline)
sys.stdout.flush()
When output is displayed using System.out.print(), the output is displayed properly. However, when a prompt for user input is printed with System.out.print(), the output is not displayed. I tried switching p.stdout.readline() to p.stdout.read(), but then no output is displayed. Is there a way to display an input prompt that does not have a carriage return?
EDIT
For example, if the Java class contains the following:
System.out.println("Message 1);
System.out.println("Message 2);
System.out.print("Enter a number:")
Running the pure Java code would display all 3 lines.
The code running through Python would only display the following:
Message 1
Message 2
p1 = subprocess.Popen(["/usr/bin/java", "MyClass"], stdout=subprocess.PIPE)
print p1.stdout.read()
Related
This question already has answers here:
Java Runtime Exec With White Spaces On Path Name
(2 answers)
Closed 5 months ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
I'm trying to run a bash cmd that grabs infomation from the google api using my api key. I run the code in the terminal and I get the output that I want (which is the address alone). But when I try use the call within java it doesnt work. I believe it ends up being a null call.
The cmd is as follows:
"wget -O- -q "https://maps.google.com/maps/api/geocode/json?address=4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan&key=[MY_API_KEY]"|grep '"formatted_address"'|cut -d\: -f2
This is my current java code
public static void main(String[] args) throws Exception {
Process runtime = Runtime.getRuntime().exec("wget -O- -q \"https://maps.google.com/maps/api/geocode/json?address=4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan&key=[MY_API_KEY]\"|grep '\"formatted_address\"'|cut -d\\: -f2");
Show_Output(runtime);
}
public static void Show_Output(Process process) throws IOException {
BufferedReader output_reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
while ((output = output_reader.readLine()) != null) {
System.out.println(output);
}
System.out.println(output);
}
Desired output is:
"4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan",
With the Process class you can only execute a single command. You on the other hand have 3:
wget -O- -q "https://maps.google.com/maps/api/geocode/json?address=4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan&key=[MY_API_KEY]"
grep '"formatted_address"'
cut -d: -f2
I see 4 options:
create a shell script that contains these commands, and execute that
create 3 processes (one for each command), and chain their input / output streams.
use a process only for the curl command, and perform the grep and cut in Java
skip using commands completely, and just use Java for the entire thing
I'd personally go for option 4. With Java's own HttpClient this should be pretty straight forward.
use HttpClient to get the response as a string
use response.lines() to get a stream of lines
use filter to replace grep (.filter(line -> line.contains("...")))
use string manipulation to replace cut
This question already has answers here:
How to get input via command line in Java? [closed]
(4 answers)
Closed 1 year ago.
this may be blurry to grasp but i'm new to java whole thing and i want to know how can i use cmd to type something in user input
E:\My apps\Java apps\test\src\main\java>java ls.java && echo E:/
enter File name or path :
in this input i want to enter the path via cmd the "&& echo E:/" doesn't work
You can use "Command Line Arguments" in order to give the input when running the program!
Assuming your file name is ls.java
compile it using: javac ls.java
when running it using java command type the arguments in front of it like:
java ls E:/path
Now you can catch the arguments in the program
public class ls {
public static void main(String[] args)
{
String path = args[0];
}
}
you can add more arguments by spaces and catch them in String array
java ls E:/path 100 200
System.out.println(args[1]); // will print 1
System.out.println(args[2]; //will print 200
NOTE: As implied all the command line arguments are stored in the form of String, if you want to convert them to another format, you'd need to parse them using methods.
This question already has answers here:
System.console() returns null
(13 answers)
Closed 5 years ago.
If i run this code below in Netbeans
import java.io.Console;
public class Introduction {
public static void main(String[] args) {
Console console= System.console();// creates a java Object which has method that allows us to write
console.printf("Hallo parvel");
}
}
It gives me the error:
Exception in thread "main" java.lang.NullPointerException
at Introduction.main(Introduction.java:10)
/home/parvel/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds).
please help
java.io.Console object is null because there is no console attached to it.
Try to run from command line or attached console to it.
Find more details about it here: https://netbeans.org/bugzilla/show_bug.cgi?id=111337
You need to run this from a terminal using java -jar myjar.jar
In order to have this print to console using System.console();
You will need to export this as a runnable jar
then you can run java -jar myjar.jar and it will output Hallo parvel
This question already has answers here:
System.console() returns null
(13 answers)
Closed 8 years ago.
I am working on a legacy app which depends on user command line input:
String key = System.console().readLine("Please enter the license key: ");
However, I am getting a NullPointerException because System.console() gives me a null.
Why does System.console() return null for a command line app? It happens when running it out of the terminal as well as IDE.
If you start java from a terminal window, then it really should work, even though I haven't tried on OSX.
If you run a simple test using java directly from the terminal, does it work?
echo 'public class Test { public static void main(String[] args) {System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test
Expected output:
hello world
If it doesn't work, then sorry, no console support on your platform.
However, if it works, and your program doesn't then there is a problem with how your program is started.
Check how the java binary started? Is it started from a shell script? Check that stdin/stdout have not been redirected or piped into something, and possibly also that it's not started in the background.
ex: This will probably make System.console() return null.
java Test | tee >app.log
and this:
java Test >/tmp/test.log
This seems to work on my machine (linux)
java Test &
Neither does it seem as if System.setOut, System.setErr or System.setIn affects the console, even after a couple of gc's and finalizers.
However:
Closing (the original) System.out or System.in will disable the console too.
echo 'public class Test { public static void main(String[] args) {System.out.close();System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test
Expected output:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:1)
So; scan your code for places where it closes streams, or passes System.out somewhere it might get closed.
To read from Standard input (command line input) you must use some kind of stream reader to read the System.in stream.
An InputStreamReader initialised by
InputStreamReader(System.in)
lets you read character by character.
However, I suggest wrapping this with a BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = reader.readLine();
Must import
java.io.*;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling Java app with “subprocess” from Python and reading the Java app output
Basically what I am looking for is, I want to interact with java program while its running using python so I can access its output and pass input to it.
I have managed to run a Java program using python. I want to know can i access the outputs of java program in my python program.
For example.
In java program: System.out.println("Enter no.");
In python i should be able to get "Enter no" as string and also pass value to java program from python.a
What I managed to do till no :
Python program :
import sys
import os.path,subprocess
def compile_java(java_file):
subprocess.check_call(['javac', java_file])
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
subprocess.call(cmd, shell=False)
def run_java(java_file):
compile_java(java_file)
execute_java(java_file)
Java Program :
import java.io.*;
import java.util.*;
class Hi
{
public static void main(String args[])throws IOException
{
Scanner t=new Scanner(System.in);
System.out.println("Enter any integer");
int str1=t.nextInt();
System.out.println("You entered"+str1);
}
}
Thanx :)
If all you need is to get the output from a non-interactive execution of your Java program, use subprocess.check_output instead of subprocess.call.
http://docs.python.org/library/subprocess.html
You need Python 2.7 or newer for check_output to be available.
If you need to interact with the Java program, you can do so using Popen.communicate, where you can read the process's output and send stuff to its input using file descriptors.
You can also use the pexpect python library to automate this kind of interaction, pexpect abstracts a lot of the legwork involved in using Popen.communicate.
Note that these techniques apply for any kind of executable you need your Python program to interact with, not just Java; as long as it uses stdin and stdout, using these calls should work for you.
The easiest way would be to use Jython, which is a complete Python implementation that runs in the JVM, and can interact with native Java code. But if you want to use CPython, and generally continue down the path you've sketched out above, you'll want to create a live Python Popen object that you can interact with. For example:
import sys
import os.path,subprocess
def compile_java(java_file):
subprocess.check_call(['javac', java_file])
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
return subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def run_java(java_file):
compile_java(java_file)
process = execute_java(java_file)
for i in range(10):
process.stdin.write(str(i) + "\n")