3

I want to execute java main class main.java by python using subprocess.Popen(). main.java takes 3 args.

I wonder how to do it? For example I have a HelloWorld.java class:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!" + args[0]);
    } }

I tried to call it in python using the command:

print (subprocess.Popen('java C:/Users/testing/Hello.Main sayHello', shell=True, stdout=subprocess.PIPE).stdout.read())

where 'sayHello' is the string args I want to pass in. It said

Error: Could not find or load main class C:.Users.testing.Hello.Main

Thanks

1 Answer 1

1

You may run your java file with extension .class the following way:

java your.path.Main arg1 arg2

where,

  • java - command, which runs the Java interpreter
  • your.path.Main - full name of your class (without .class)
  • arg1 arg2 - the arguments (written by spaces or between ")

Further, when you formatted this line, it transmits in subprocess.Popen() as argument.

subprocess.Popen('java your.path.Main arg1 arg2')

I'm not Python programmer, because I advice you to read documentation about this method.

Sign up to request clarification or add additional context in comments.

5 Comments

note: it won't work on POSIX systems; use a list argument instead: 'java your.path.Main arg1 arg2'.split()
I tried it with simple helloworld class using: print (subprocess.Popen('java C:/Users/Testing/src/HelloWorld.Main', shell=True, stdout=subprocess.PIPE).stdout.read()) and got the error: Error: Could not find or load main class C:.Users.src.Hello
@AndrewTobilko I did make HelloWorld.class and got that error which is why I don't get the reason :) and thanks for such a fast response
@AndrewTobilko it works perfectly on command prompt when I was in the correct directory, but doesn't work when I typed in entire path such as java C:/Users/testing/HelloWorld it will return same error: Error: Could not find or load main class C:.Users.testing.HelloWorld it may be the problem since in python, I also put in full path like that

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.