0

I am creating a python script which does the following task: 1)list all files in directory 2) if the files found are of .java type then 3) it compiles the java file using subprocess.check_call 4) if there is no error it then executes the file using its class name which is same as file name

now some file requires an user input during run time. That's exactly where I am stuck. My script compiles and runs the java program. but whenever my java program asks for input,"Enter The Number :" , my script does not takes the input due to which following error is thrown:

Enter the Number

Exception in thread "main" java.lang.NumberFormatException: null

at java.lang.Integer.parseInt(Integer.java:415)

at java.lang.Integer.parseInt(Integer.java:497)

at inp.main(inp.java:17)

I want that the screen should wait for my input and when i enter the number it resumes its execution

my java program is:

import java.io.*;
class inp
{
    public static void main(String args[])throws IOException
    {
        InputStreamReader in=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(in);
        System.out.println("Enter the Number");
        int n=Integer.parseInt(br.readLine());
        int b=10*n;
        System.out.println("T 10 multiple of Number is : "+b);
    }
}

my python script is :

import subprocess
import sys
import os

s=os.getcwd()
s="codewar/media/"
print os.chdir(s)
t=os.getcwd()
print os.listdir(t)
for file in os.listdir(t):
    if file.endswith(".java"):
        proc=subprocess.check_call(['javac',file])
        print proc
        if proc==0:
            l=file.split(".")
            proc=subprocess.Popen(['java',l[0]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            input=subprocess.Popen(['java',l[0]],shell=True,stdin=subprocess.PIPE)
            print proc.stdout.read()

Please point the error or tell me a new way to do it.

2 Answers 2

1

to give the user input when asked in java while executing the script through python

#!/usr/bin/env python
import os
from glob import glob
from subprocess import Popen, PIPE, call

wdir = "codewar/media"

# 1) list all .java files in directory
for path in glob(os.path.join(wdir, "*.java")):
    # 2) compile the java file
    if call(['javac', path]) != 0: # error
        continue
    # 3) if there is no error it then executes the file using its 
    # class name which is same as file name
    classname = os.path.splitext(os.path.basename(path))[0]
    p = Popen(['java', '-cp', wdir, classname], 
              stdin=PIPE, stdout=PIPE, stderr=PIPE,
              universal_newlines=True) # convert to text (on Python 3)
    out, err = p.communicate(input='12345')
    if p.returncode == 0:
        print('Got {result}'.format(result=out.strip().rpartition(' ')[2]))
    else: # error
        print('Error: exit code: {}, stderr: {}'.format(p.returncode, err))

The key as @user2016436 suggested is to use .communicate() method here.


But I want in such a way that while its running and displays enter a number : the screen should wait for my input and when i enter the number it resumes its execution

If you don't need to capture the output and you want to provide the input manually from the keyboard then you don't need to use Popen(.., PIPE) and .communicate(), just use call() instead:

#!/usr/bin/env python
import os
from glob import glob
from subprocess import call

wdir = "codewar/media"

# 1) list all .java files in directory
for path in glob(os.path.join(wdir, "*.java")):
    # 2) compile the java file
    if call(['javac', path]) != 0: # error
        continue
    # 3) if there is no error it then executes the file using its
    # class name which is same as file name
    classname = os.path.splitext(os.path.basename(path))[0]
    rc = call(['java', '-cp', wdir, classname])
    if rc != 0:
        print('Error: classname: {} exit code: {}'.format(classname, rc))
Sign up to request clarification or add additional context in comments.

13 Comments

I used your code but when I am running the script i get following error :Error: exit code: 1, stderr: java.lang.NoClassDefFoundError: check Exception in thread "main" Error: exit code: 1, stderr: java.lang.NoClassDefFoundError: inp Exception in thread "main"
@user3010409: I've added classpath to the java command so that the class could be found.
thats okay sir, But I want in such a way that while its running and displays enter a number : the screen should wait for my input and when i enter the number it resumes its execution
don't put additional info in the comments. Update your question instead.
I did so, please help now.
|
0

Firstly, instead of:

proc=subprocess.Popen(['java',l[0]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
input=subprocess.Popen(['java',l[0]],shell=True,stdin=subprocess.PIPE)

it should be:

proc=subprocess.Popen(['java',l[0]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True,stdin=subprocess.PIPE)

Secondly, use Popen.communicate to communicate with the subprocess, i.e., feed it with input. In your example:

(stdoutdata, stderrdata) = proc.communicate('2')

will pass '2' to the subprocess, and return the stdout and stderr of the subprocess.

2 Comments

when I am doing the changes as suggested by you I am getting output as 0 0 and nothing else. Neither "enter your number" nor any message..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.