Import classes in jar files directly from Python scripts

This is a method to import the class in the jar file directly from the Python script.

It doesn't depend on CLASSPATH, so if you have an environment where Java and Jython can run It makes it possible to easily package the integration between Python and Java.

This is useful, for example, when you want to use Java's legacy and SQLite at the same time in Python. Jython is a standard module and does not support SQLite, so a JDBC driver is required, If you can read the JDBC driver jar file directly from the Python script, You can use Java classes and SQLite from Python just by throwing in the files you need.

Tweak sys.path

test.py


import.sys
sys.path.append("/path/to/hogehoge.jar")
import Hogehoge

It works with! There was information that it was useless. It seems that you have to load the classes in it, not just pass it through.

ClassPathHacker

ClassPath Hacker seems to be one solution. http://www.jython.org/jythonbook/en/1.0/appendixB.html#working-with-classpath

The following is an example of calling the JDBC driver of sqlite from jython.

test2.py


from java.lang import Class
from java.sql import DriverManager

class classPathHacker:
    import java.net.URLClassLoader

    def addFile(self, s):
        sysloader = self.java.lang.ClassLoader.getSystemClassLoader()
        sysclass = self.java.net.URLClassLoader
        method = sysclass.getDeclaredMethod("addURL", [self.java.net.URL])
        method.setAccessible(1)
        f = self.java.io.File(s)
        method.invoke(sysloader, [f.toURL()])

c = classPathHacker()
c.addFile("/path/to/sqlite-jdbc.jar")
jdbc_url = "jdbc:sqlite:/path/to/database.db"
driver = "org.sqlite.JDBC"
Class.forName(driver).newInstance()
con = DriverManager.getConnection(jdbc_url)
#Below

I'm not sure, but forcibly make URLClassLoader.addURL accessible It looks like you're loading a class.

Recommended Posts

Import classes in jar files directly from Python scripts
Dynamically import scripts in Python
Extract strings from files in Python
Python from or import
How to download files from Selenium in Python in Chrome
OCR from PDF in Python
Recursively copy files from the directory directly under the directory using Python
Allow Python to select strings in input files from folders
Transpose CSV files in Python Part 1
Working with LibreOffice in Python: import
Get data from Quandl in Python
Manipulate files and folders in Python
Read and use Python files from Python
Handling of JSON files in Python
Download Google Drive files in Python
About Python, from and import, as
Sort large text files in Python
Read files in parallel with Python
Run Python scripts synchronously from C #
Export and output files in Python
python> link> from __future__ import print_function> Make Python 3.X print () available in Python 2.X
Check installed modules from Python scripts
Run Python Scripts from Cisco Memorandum_EEM
Reading from text files and SQLite in Python (+ Pandas), R, Julia (+ DataFrames)
Get options in Python from both JSON files and command line arguments
Find files like find on linux in Python
Output tree structure of files in Python
Revived from "no internet access" in Python
Prevent double boot from cron in Python
Pharmaceutical company researchers summarized classes in Python
PUT gzip directly to S3 in Python
Type annotations for Python2 in stub files!
I want to use jar from python
Decrypt files encrypted with openssl from python with openssl
Referencing INI files in Python or Ruby
I can't debug python scripts in Eclipse
Template for writing batch scripts in python
Automate jobs by manipulating files in Python
Download images from URL list in Python
Get battery level from SwitchBot in Python
Read and write JSON files in Python
Sample for handling eml files in Python
Generate a class from a string in Python
Generate C language from S-expressions in Python
Convert from Markdown to HTML in Python
Get Precipitation Probability from XML in Python
Download files in any format using Python
Module import and exception handling in python
Import Error in Python3: No module named'xxxxx'
Get metric history from MLflow in Python
I want to get / execute variables / functions / classes of external files from Python
Send an email directly by pulling an MX record from your email address in Python
Get time series data from k-db.com in Python
[Python] Get the files in a folder with Python
Convert FBX files to ASCII <-> BINARY in Python
Study from Python Hour7: How to use classes
Type Python scripts to run in QGIS Processing
Import Excel file from Python (register to DB)
Study from Python Reading and writing Hour9 files
Resolve Japanese write error UnicodeEncodeError in Python files
From file to graph drawing in Python. Elementary elementary