2
votes

I wanted to import a java package "TestPackage" into jython script,

import TestPackage
print TestPackage.SampleClass().getMessage();

I am getting the following error,

ImportError: No module named TestPackage","errorPoint":"","lineNumber":"1","errorPointMessage":"in <module>\nImportError: No module named TestPackage

When I use from TestPackage import SampleClass works fine. If I execute from <pacakage> import <anyclass> statement once, then import <pacakage> works without the import error.

I tried setting PySystemState.add_package("TestPackage"), this works but leading to memory leakage.

Is there any alternative way to make use of import TestPackage ? How can I use "import <packagename>" in jython without memory leakage?

1
What's the full package name of TestPackage? For example, org.example.test.TestPackage would be imported as import org.example.test.TestPackage or from org.example.test import TestPackage. Same as in Java :) If the jar file isn't on your Jython classpath, add it. As a quick hack, import sys; sys.path.append('/path/to/testpackage.jar') works. - IceArdor
It's in the class path with package name as "TestPackage". - Kajal

1 Answers

0
votes

This is due to a difference in Java and Python.

In Java you can import classes, and static import constants and static methods. You cannot import a package. import java.util; is a compile error, but import java.util.Collections; or import java.util.Collections.*; are fine. A Java package is a way of organizing a bunch of classes but doesn't isn't a class with a constructor, methods, or constants. I like to think of a Java package as a zip file containing all the classes that belong to that package. A Java package is merely a namespace.

In Python you can import modules, classes, and from-import classes, functions, and constants. However, a Python module is a lot more like a Java class than a Java package. It is not merely a "zip file of classes", but a class that contains subclasses. A Python module is a collection of scripts in a folder with an init.py, which defines classes and methods for that module. Thus, you can do things like import collections. Python also lets you do import collections.OrderedDict, from collections import OrderedDict, and from collections import OrderedDict as OD.

I hope this explains why you can't import your Java package. You have to import something (probably a class) from that Java package in order for python to create a variable.