Skip to content

Commit fd30db2

Browse files
committed
bugfix: install pth
1 parent 51a05f3 commit fd30db2

File tree

7 files changed

+88
-381
lines changed

7 files changed

+88
-381
lines changed

README.ja.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,17 @@ python -m jvm --install-stub
5858
python -m jvm --uninstall-stub
5959
```
6060

61+
### PTH ファイルインストール
62+
63+
仮想環境で自動的に JVM インポートを有効にする .pth ファイルをインストール:
64+
65+
```bash
66+
# 自動インポート用の jvm.pth ファイルをインストール
67+
python -m jvm --install-pth
68+
```
69+
70+
これにより、仮想環境の `site-packages` ディレクトリに `jvm.pth` ファイルが作成され、Python 起動時に自動的に JVM モジュールがインポートされ、手動初期化なしでシームレスに Java クラスをインポートできるようになります。
71+
6172
### 機能
6273

6374
**型スタブ管理:**
@@ -67,6 +78,12 @@ python -m jvm --uninstall-stub
6778
- **自動生成**: 必要に応じて JVM インストールから新しいスタブを生成
6879
- **仮想環境検出**: venv、virtualenv、conda、その他の Python 環境マネージャーと連携
6980

81+
**PTH ファイル管理:**
82+
83+
- **PTH ファイルインストール**: Python 起動時に自動的に JVM モジュールをインポートする `jvm.pth` ファイルを仮想環境に作成
84+
- **自動インポート**: 手動の JVM 初期化なしでシームレスな Java クラスインポートを実現
85+
- **仮想環境安全性**: アクティブな仮想環境内でのみ動作し、分離されたセットアップを保証
86+
7087
**サポートされるパッケージ:**
7188

7289
- `java.lang` - Java コアクラス (String、System、Object 等)
@@ -91,6 +108,9 @@ pip install jvm
91108
# IDEサポート用の型スタブをインストール
92109
python -m jvm --install-stub
93110

111+
# または自動JVMインポート用のPTHファイルをインストール
112+
python -m jvm --install-pth
113+
94114
# IDEで自動補完が利用可能になります
95115
from java.lang import System # IDEが利用可能なメソッドを表示
96116
```
@@ -104,18 +124,21 @@ python -m jvm --help
104124
出力:
105125

106126
```
107-
usage: jvm [-h] (--install-stub | --uninstall-stub)
127+
usage: jvm [-h] (--install-stub | --uninstall-stub | --install-pth)
108128
109129
JVM-PyBind: Python bindings for JVM with type stub management
110130
111131
options:
112132
-h, --help show this help message and exit
113133
--install-stub Install JDK type stubs to the current virtual environment
114134
--uninstall-stub Remove JDK type stubs from the current virtual environment
135+
--install-pth Install jvm.pth file to enable automatic JVM import in
136+
virtual environment
115137
116138
Examples:
117139
python -m jvm --install-stub Install JDK type stubs to virtual environment
118140
python -m jvm --uninstall-stub Remove JDK type stubs from virtual environment
141+
python -m jvm --install-pth Install jvm.pth file to enable automatic JVM import
119142
```
120143

121144
### カスタム Java クラスの使用 (実験的機能)

README.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,17 @@ Remove type stubs when no longer needed:
5858
python -m jvm --uninstall-stub
5959
```
6060

61+
### PTH File Installation
62+
63+
Install a .pth file to enable automatic JVM import in your virtual environment:
64+
65+
```bash
66+
# Install jvm.pth file for automatic import
67+
python -m jvm --install-pth
68+
```
69+
70+
This creates a `jvm.pth` file in your virtual environment's `site-packages` directory that automatically imports the JVM module when Python starts, enabling seamless Java class imports without manual initialization.
71+
6172
### Features
6273

6374
**Type Stub Management:**
@@ -67,6 +78,12 @@ python -m jvm --uninstall-stub
6778
- **Auto-generation**: Generates fresh stubs from your JVM installation if needed
6879
- **Virtual environment detection**: Works with venv, virtualenv, conda, and other Python environment managers
6980

81+
**PTH File Management:**
82+
83+
- **Install PTH file**: Creates a `jvm.pth` file in your virtual environment that automatically imports the JVM module at Python startup
84+
- **Automatic import**: Enables seamless Java class imports without manual JVM initialization
85+
- **Virtual environment safety**: Only works within active virtual environments for isolated setup
86+
7087
**Supported Packages:**
7188

7289
- `java.lang` - Core Java classes (String, System, Object, etc.)
@@ -91,6 +108,9 @@ pip install jvm-pybind
91108
# Install type stubs for IDE support
92109
python -m jvm --install-stub
93110

111+
# OR install PTH file for automatic JVM import
112+
python -m jvm --install-pth
113+
94114
# Now you get autocompletion in your IDE
95115
from java.lang import System # IDE will show available methods
96116
```
@@ -104,18 +124,21 @@ python -m jvm --help
104124
Output:
105125

106126
```
107-
usage: jvm [-h] (--install-stub | --uninstall-stub)
127+
usage: jvm [-h] (--install-stub | --uninstall-stub | --install-pth)
108128
109129
JVM-PyBind: Python bindings for JVM with type stub management
110130
111131
options:
112132
-h, --help show this help message and exit
113133
--install-stub Install JDK type stubs to the current virtual environment
114134
--uninstall-stub Remove JDK type stubs from the current virtual environment
135+
--install-pth Install jvm.pth file to enable automatic JVM import in
136+
virtual environment
115137
116138
Examples:
117139
python -m jvm --install-stub Install JDK type stubs to virtual environment
118140
python -m jvm --uninstall-stub Remove JDK type stubs from virtual environment
141+
python -m jvm --install-pth Install jvm.pth file to enable automatic JVM import
119142
```
120143

121144
### Working with Custom Java Classes (Experimental)

pyproject.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
[project]
22
name = "jvm-pybind"
3-
version = "0.1.0rc2"
3+
version = "0.1.0rc3"
44
description = "JVM bindings for Python that enable seamless integration between Python and Java code through JNI (Java Native Interface)."
55
readme = "README.md"
66
authors = [{ name = "t3tra-dev", email = "[email protected]" }]
7-
license = { text = "MIT" }
87
classifiers = [
98
# How mature is this project? Common values are
109
# 3 - Alpha

src/jvm/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,4 @@
2525
"__version__",
2626
]
2727

28-
__version__ = "0.1.0rc2"
28+
__version__ = "0.1.0rc3"

src/jvm/cli.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,26 @@ def uninstall_stubs(self) -> bool:
221221
logger.info("✓ Stub uninstallation completed!")
222222
return True
223223

224+
def install_pth(self) -> bool:
225+
"""JVM .pth ファイルインストール"""
226+
site_packages = self.venv_detector.detect_venv()
227+
if not site_packages:
228+
self._log_venv_error()
229+
return False
230+
231+
pth_file = site_packages / "jvm.pth"
232+
logger.info(f"Installing jvm.pth to: {pth_file}")
233+
234+
try:
235+
with open(pth_file, "w", encoding="utf-8") as f:
236+
f.write("import jvm\n")
237+
logger.info("✓ jvm.pth file installed successfully!")
238+
logger.info("Now you can use 'from java.lang import System' directly in any Python script")
239+
return True
240+
except Exception as e:
241+
logger.error(f"Failed to create jvm.pth file: {e}")
242+
return False
243+
224244

225245
def create_parser() -> argparse.ArgumentParser:
226246
"""Create command line argument parser"""
@@ -232,6 +252,7 @@ def create_parser() -> argparse.ArgumentParser:
232252
Examples:
233253
python -m jvm --install-stub Install JDK type stubs to virtual environment
234254
python -m jvm --uninstall-stub Remove JDK type stubs from virtual environment
255+
python -m jvm --install-pth Install jvm.pth file to enable automatic JVM import
235256
""",
236257
)
237258

@@ -246,6 +267,11 @@ def create_parser() -> argparse.ArgumentParser:
246267
action="store_true",
247268
help="Remove JDK type stubs from the current virtual environment",
248269
)
270+
group.add_argument(
271+
"--install-pth",
272+
action="store_true",
273+
help="Install jvm.pth file to enable automatic JVM import in virtual environment",
274+
)
249275
return parser
250276

251277

@@ -261,6 +287,8 @@ def main() -> int:
261287
success = installer.install_stubs(force_regenerate=False)
262288
elif args.uninstall_stub:
263289
success = installer.uninstall_stubs()
290+
elif args.install_pth:
291+
success = installer.install_pth()
264292
else:
265293
parser.print_help()
266294
return 1

src/jvm/typeconv.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,15 @@ def to_python(jvm: JVM, jobject: Any) -> object:
3333
if isinstance(jobject, (dict, list, tuple, set)):
3434
return jobject
3535

36+
# Try to get object class first
3637
try:
37-
cls = jvm.jni.GetObjectClass(jobject) # noqa
38+
jvm.jni.GetObjectClass(jobject)
3839
except (TypeError, ValueError, ctypes.ArgumentError):
40+
# If we can't get the class but jobject looks like a valid JNI reference,
41+
# create an ObjectProxy anyway
42+
if isinstance(jobject, (int, ctypes.c_void_p)) and jobject != 0:
43+
from .proxy import ObjectProxy
44+
return ObjectProxy(jvm, jobject)
3945
return jobject
4046

4147
# String
@@ -60,4 +66,6 @@ def to_python(jvm: JVM, jobject: Any) -> object:
6066
raise RuntimeError("Could not find Integer.intValue method")
6167
return int(jvm.jni.CallIntMethod(jobject, mid))
6268

63-
return jobject
69+
# For any other Java object, create an ObjectProxy
70+
from .proxy import ObjectProxy
71+
return ObjectProxy(jvm, jobject)

0 commit comments

Comments
 (0)