2

I have a Java project that makes use of the Jython library. I can build the code and execute it fine either in Eclipse or from the command line, however, when I package the project into a JAR file, I get the following error:

ImportError: no Module named socket

I know what this error means, and socket is the first module in the Python script in question. Why won't this run from a JAR file? Jython.jar is also packaged inside of the JAR I built so I would think it should be able to find it. Any ideas?

2 Answers 2

2

I was having similar issues until I discovered that there are actually two Jython jars -- jython.jar and jython-standalone.jar. The standalone jar includes all the standard python Lib modules. Using that seemed to fix my import-related woes.

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

Comments

1

When running from Eclipse (which manages the classpath for you) or from the command line (where I'm guessing you are specifying the classpath when you run it) you are including Jython.jar on the classpath.

Sadly, including other jars inside of your jar is not sufficient to place that jar on the classpath. You could extract the entire Jython.jar and include the extracted files in your jar (later versions of Eclipse do this when you export with the Runnable JAR File option.

However, this could lead to issues if Jython code expected it to be in a JAR, if there were namespace conflicts, or legal issues (in many cases it's illegal to extract a 3rd party jar and redistribute it as your own).

To confirm this, try running your jar outside of Eclipse, including jython.jar on the classpath. For example:

java -cp lib/jython.jar:myjar.jar com.me.main.Main

Keep in mind that if you use the -jar option (e.g. main class attribute) then the -cp flag is ignored so this will not work if you do:

java -cp lib/jython.jar -jar myjar.jar

If it is the issue then there are a number of ways to include jython.jar on the classpath automatically. Two popular approaches are to use the classpath attribute on the manifest (works as long as you can guarantee jython.jar's location relative to your main jar) or to wrap the execution of your jar in a shell script.

2 Comments

Is there a way to edit the classpath in the manifest so that it references the JAR packaged in the main JAR?
I found out the issue, but don't really have much of a solution at this time. I looked inside the JAR, and it turns out the Python module is not being built into the JAR. If I drop it in the root of the JAR using an archive manager, the JAR runs as intended every time. But you were right @Pace, clearly the Python module was not on the classpath, as it was not in the JAR.

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.