Building a Java Application
You can build a complete application in Jython that looks and behaves like a Java program: a main entry point, Java classes for structure, command-line arguments, and files - while keeping the code in Python. This is the pattern for JVM tools where the team thinks in Java but wants Python's brevity.
The Main Entry Point
import sys
def main(argv):
if not argv:
print("usage: jython app.py <input> <output>")
return 1
input_path, output_path = argv[0], argv[1]
with open(input_path) as fin, open(output_path, "w") as fout:
for line in fin:
fout.write(line.upper())
print(f"wrote {output_path}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Defining Java-Style Classes in Jython
import java.io
class Report:
def __init__(self, title):
self.title = title
self.lines = []
def add(self, line):
self.lines.append(line)
def write_to(self, path):
w = java.io.FileWriter(path)
try:
w.write(self.title + "\n")
for line in self.lines:
w.write(line + "\n")
finally:
w.close()
r = Report("Daily Report")
r.add("ok: 120")
r.add("fail: 2")
r.write_to("report.txt")
Threading (True Parallelism)
Jython threads are real OS threads - no GIL. CPU-bound work scales across cores:
import threading
def worker(n):
total = sum(i * i for i in range(n))
print(f"worker done {n}")
threads = [threading.Thread(target=worker, args=(10**6,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("all workers finished")
Configuration and Logging
import java.util.logging as jlog
logger = jlog.Logger.getLogger("MyApp")
logger.info("starting application")
logger.warning("config file missing, using defaults")
Or use the Python logging module - both work, but pick one per application for consistent output.
Packaging the Application
- Bundle your .py files plus any third-party jars into a directory or zip.
- Provide a launcher script (shell/batch) that calls jython -cp "jars/*" app.py with the user's arguments.
- For deployment, GraalVM can compile Jython/Java apps to a standalone image if startup time matters.
Summary
A Jython application is a Python program with a main entry point, classes for structure, threading for parallel work, and Java APIs (files, logging, collections) used directly. Package it with its jars and a launcher script, and you have a JVM application written in a fraction of Java's lines.