How to load data files into Jython module?

I have some Jython modules that I am trying to make from a JAR. Everything is fine tuned, except that some modules expect to open files from the file system, which are located in the same directory as the Python script itself. This no longer works because these files are now included in the JAR.

Basically, I want to know if there is an equivalent to the Class.getResourceAsStream () class that I can use from Python code to load these data files. I tried to use '__pyclasspath__/path/to/module/data.txt' but it was not there.

+4
source share
3 answers

Java Class.getResourceAsStream() uses the Java class loading system to search for a resource. The Python class loading mechanism is designed to provide some of these features. Most of them are described here and in PEP 302 .

A summary of this:

  • when the python module loads, the loader must set the __loader__ attribute
  • the bootloader must support additional methods for retrieving data from a single source

By default, zipimporter , which is used when python classes are loaded from zip or jarfiles, fortunately supports these methods. Therefore, if you know that the data file is in the same bank as the python module, you can use its loader to load:

 import some_module data = some_module.__loader__.get_data("path/in/archive/file.txt") 
+4
source

Maybe I just miss the point, but can you use getResourceAsStream () in the Java class?

0
source

I had the same problem, but I'm not sure that my circumstances were exactly the same. I did not see an exception due to the lack of get_data , until I pushed my .jar to the network and tried to use it on WebStart (local hosting of WebStarting and running jar using java -jar worked fine).

Anyway, this is how I solved my problem:

 import SomeClass url = SomeClass.getClassLoader().findResource('path/to/resource.txt') inputStream = url.openStream() # ... 

SomeClass is the Java class in my .jar file. This is most likely the Java class that I use to run the Jython interpreter, so I know that it will always be there.

0
source

Source: https://habr.com/ru/post/1482267/


All Articles