Run a Java main class using its relative path? (Python)

I am using Python to execute the JVM for a specified Java class, like so:

import subprocess
output = subprocess.check_output("java MyJavaClass")

However, the Java class is not in the same directory as the Python script, so this does not work. It is in a bin directory two directories up.

So I was hoping it would be possible to do something like below, but it doesn't work:

output = subprocess.check_output("java ../../bin/MyJavaClass")

Any ideas?

Upvotes: 0

Views: 872

Answers (2)

erikxiv
erikxiv

Reputation: 4075

Try

output = subprocess.check_output("java MyJavaClass", cwd="../../bin/")

When running Java, the directory structure implies a package structure, so it is required to execute java from the correct directory (unless using classpath).

Upvotes: 1

Moritz Petersen
Moritz Petersen

Reputation: 13047

You need to set the classpath, like this:

java -classpath ../../bin MyJavaClass

Please note, that if your class belongs to a certain package, you have to use the FQN (Full Qualified Name):

java -classpath ../../bin my.package.MyJavaClass

Upvotes: 3

Related Questions