or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

autoclass.mdenvironment.mdindex.mdmanual-classes.mdsignatures.mdutilities.md

environment.mddocs/

0

# Environment and Setup

1

2

PyJNIus provides comprehensive Java environment detection and configuration for different platforms. The environment system automatically discovers Java installations, handles platform-specific JVM loading, and manages classpath configuration. It also includes JVM configuration utilities for setting options and classpath before JVM startup.

3

4

## Capabilities

5

6

### Java Environment Detection

7

8

Main function for getting platform-specific Java environment configuration.

9

10

```python { .api }

11

def get_java_setup(platform: str = None) -> JavaLocation:

12

"""

13

Get platform-specific Java environment configuration.

14

15

Args:

16

platform: Target platform ('win32', 'android', or None for auto-detection)

17

18

Returns:

19

JavaLocation object with Java environment information

20

21

Note:

22

Automatically detects and configures Java environment based on

23

JAVA_HOME, JDK_HOME, JRE_HOME environment variables and system paths.

24

"""

25

```

26

27

### JavaLocation Object

28

29

The JavaLocation object returned by `get_java_setup()` provides access to Java environment details:

30

31

```python { .api }

32

class JavaLocation:

33

"""Java environment configuration object."""

34

35

def get_javahome() -> str:

36

"""Get Java home directory path."""

37

38

def get_javac() -> str:

39

"""Get javac compiler executable path."""

40

41

def get_libraries() -> list:

42

"""Get list of required JNI libraries."""

43

44

def get_library_dirs() -> list:

45

"""Get list of library search directories."""

46

47

def get_include_dirs() -> list:

48

"""Get list of JNI header include directories."""

49

50

def is_jdk() -> bool:

51

"""Check if installation is JDK (includes compiler) vs JRE only."""

52

```

53

54

### Environment Variables

55

56

PyJNIus respects the following environment variables for Java detection:

57

58

- **JAVA_HOME**: Primary Java installation directory

59

- **JDK_HOME**: JDK-specific installation directory

60

- **JRE_HOME**: JRE-specific installation directory

61

- **CLASSPATH**: Additional Java classpath entries

62

63

**Environment Variable Priority:**

64

1. JAVA_HOME (highest priority)

65

2. JDK_HOME

66

3. JRE_HOME

67

4. System default Java installation

68

69

### Platform-Specific Behavior

70

71

**Desktop Platforms (Windows, Linux, macOS):**

72

- Automatic JVM library loading from standard locations

73

- Support for both JDK and JRE installations

74

- Dynamic library path resolution

75

76

**Android Platform:**

77

- Integration with python-for-android build system

78

- Automatic thread detachment for all threads

79

- Android-specific JNI library handling

80

81

**Windows-Specific:**

82

- DLL directory management for JVM loading

83

- Support for multiple JVM variants (client, server, default)

84

- Automatic library path resolution

85

86

**Usage Examples:**

87

88

### Basic Environment Setup

89

90

```python

91

from jnius.env import get_java_setup

92

93

# Get Java environment for current platform

94

java_env = get_java_setup()

95

96

print(f"Java Home: {java_env.get_javahome()}")

97

print(f"Is JDK: {java_env.is_jdk()}")

98

print(f"Libraries: {java_env.get_libraries()}")

99

print(f"Include Dirs: {java_env.get_include_dirs()}")

100

101

# Check if we can compile Java code

102

if java_env.is_jdk():

103

javac_path = java_env.get_javac()

104

print(f"Java compiler: {javac_path}")

105

else:

106

print("JRE only - no compiler available")

107

```

108

109

### Platform-Specific Setup

110

111

```python

112

from jnius.env import get_java_setup

113

import sys

114

115

# Get setup for specific platform

116

if sys.platform == 'win32':

117

java_env = get_java_setup('win32')

118

elif 'ANDROID_ARGUMENT' in os.environ:

119

java_env = get_java_setup('android')

120

else:

121

java_env = get_java_setup() # Auto-detect

122

123

# Platform-specific library handling

124

libs = java_env.get_libraries()

125

lib_dirs = java_env.get_library_dirs()

126

127

print(f"Platform: {sys.platform}")

128

print(f"Required libraries: {libs}")

129

print(f"Library directories: {lib_dirs}")

130

```

131

132

### Environment Validation

133

134

```python

135

from jnius.env import get_java_setup

136

import os

137

138

def validate_java_environment():

139

"""Validate Java environment setup."""

140

try:

141

java_env = get_java_setup()

142

143

# Check Java home exists

144

java_home = java_env.get_javahome()

145

if not os.path.exists(java_home):

146

return False, f"Java home not found: {java_home}"

147

148

# Check for JDK if needed

149

if not java_env.is_jdk():

150

return False, "JDK required but only JRE found"

151

152

# Check libraries

153

libs = java_env.get_libraries()

154

lib_dirs = java_env.get_library_dirs()

155

156

for lib_dir in lib_dirs:

157

if not os.path.exists(lib_dir):

158

return False, f"Library directory not found: {lib_dir}"

159

160

return True, "Java environment valid"

161

162

except Exception as e:

163

return False, f"Java environment error: {e}"

164

165

# Usage

166

is_valid, message = validate_java_environment()

167

print(f"Environment valid: {is_valid}")

168

print(f"Message: {message}")

169

```

170

171

### Classpath Management

172

173

```python

174

import os

175

from jnius.env import get_java_setup

176

177

def setup_classpath(additional_jars=None):

178

"""Setup Java classpath with additional JAR files."""

179

java_env = get_java_setup()

180

181

# Get existing classpath

182

existing_classpath = os.environ.get('CLASSPATH', '')

183

184

# Build new classpath

185

classpath_entries = []

186

187

if existing_classpath:

188

classpath_entries.append(existing_classpath)

189

190

if additional_jars:

191

for jar_path in additional_jars:

192

if os.path.exists(jar_path):

193

classpath_entries.append(jar_path)

194

else:

195

print(f"Warning: JAR not found: {jar_path}")

196

197

# Set classpath

198

if classpath_entries:

199

new_classpath = os.pathsep.join(classpath_entries)

200

os.environ['CLASSPATH'] = new_classpath

201

print(f"Classpath set to: {new_classpath}")

202

203

return java_env

204

205

# Usage

206

additional_jars = [

207

'/path/to/library1.jar',

208

'/path/to/library2.jar'

209

]

210

java_env = setup_classpath(additional_jars)

211

```

212

213

### JVM Configuration (jnius_config)

214

215

Functions for configuring JVM options and classpath before JVM startup. These must be called before importing jnius.

216

217

```python { .api }

218

def set_options(*opts: str) -> None:

219

"""

220

Set list of JVM options, replacing any previously set options.

221

222

Args:

223

*opts: JVM option strings (e.g., '-Xmx4096m', '-Xrs')

224

225

Raises:

226

ValueError: If JVM is already running

227

228

Note:

229

Must be called before importing jnius or JVM startup.

230

"""

231

232

def add_options(*opts: str) -> None:

233

"""

234

Append options to the list of JVM options.

235

236

Args:

237

*opts: JVM option strings to append

238

239

Raises:

240

ValueError: If JVM is already running

241

"""

242

243

def get_options() -> list:

244

"""

245

Get current list of JVM options.

246

247

Returns:

248

List of JVM option strings

249

"""

250

251

def set_classpath(*path: str) -> None:

252

"""

253

Set JVM classpath, replacing existing classpath and CLASSPATH environment variable.

254

255

Args:

256

*path: Classpath entries (directories, JAR files)

257

258

Raises:

259

ValueError: If JVM is already running

260

"""

261

262

def add_classpath(*path: str) -> None:

263

"""

264

Append items to JVM classpath.

265

266

Args:

267

*path: Classpath entries to append

268

269

Raises:

270

ValueError: If JVM is already running

271

"""

272

273

def get_classpath() -> list:

274

"""

275

Get current JVM classpath including default entries.

276

277

Returns:

278

List of classpath entries

279

280

Note:

281

Includes CLASSPATH environment variable and PyJNIus defaults.

282

"""

283

284

def expand_classpath() -> str:

285

"""

286

Expand classpath with wildcard resolution for JAR files.

287

288

Returns:

289

Platform-specific classpath string with wildcards expanded

290

"""

291

```

292

293

**Usage Examples:**

294

295

```python

296

import jnius_config

297

298

# Set JVM options before importing jnius

299

jnius_config.set_options('-Xmx4096m', '-Xrs')

300

jnius_config.add_options('-XX:+UseG1GC')

301

302

# Set classpath with additional JARs

303

jnius_config.set_classpath('.', '/path/to/library.jar', '/path/to/libs/*')

304

305

# Now safe to import jnius

306

import jnius

307

from jnius import autoclass

308

309

# Use Java classes with configured environment

310

String = autoclass('java.lang.String')

311

```

312

313

### Architecture Support

314

315

PyJNIus supports multiple CPU architectures with automatic detection:

316

317

```python { .api }

318

MACHINE2CPU: dict # Maps platform.machine() values to CPU strings

319

```

320

321

**Supported Architectures:**

322

- x86 (`i686``i386`)

323

- x86_64 (`x86_64``amd64`)

324

- ARM (`armv7l``arm`)

325

- ARM64 (`aarch64``aarch64`)

326

- SPARC (`sun4u`, `sun4v``sparcv9`)

327

328

**Usage Example:**

329

330

```python

331

from jnius.env import MACHINE2CPU, get_java_setup

332

from platform import machine

333

334

# Get current architecture

335

current_machine = machine()

336

cpu_type = MACHINE2CPU.get(current_machine, current_machine)

337

338

print(f"Machine: {current_machine}")

339

print(f"CPU Type: {cpu_type}")

340

341

# Java environment will use appropriate libraries for architecture

342

java_env = get_java_setup()

343

lib_dirs = java_env.get_library_dirs()

344

345

# Library directories often include architecture-specific paths

346

for lib_dir in lib_dirs:

347

if cpu_type in lib_dir:

348

print(f"Architecture-specific lib dir: {lib_dir}")

349

```

350

351

### Troubleshooting Environment Issues

352

353

**Common Environment Problems:**

354

355

1. **JAVA_HOME not set**: Set JAVA_HOME environment variable

356

2. **JRE vs JDK**: Ensure JDK is installed if compilation is needed

357

3. **Architecture mismatch**: Use JVM matching Python architecture (32/64-bit)

358

4. **Missing libraries**: Install complete JDK/JRE package

359

5. **Classpath issues**: Verify JAR files exist and are accessible

360

361

**Debug Environment Setup:**

362

363

```python

364

import os

365

import sys

366

from jnius.env import get_java_setup

367

368

def debug_java_environment():

369

"""Debug Java environment configuration."""

370

print("=== Java Environment Debug ===")

371

372

# Environment variables

373

print("\nEnvironment Variables:")

374

for var in ['JAVA_HOME', 'JDK_HOME', 'JRE_HOME', 'CLASSPATH']:

375

value = os.environ.get(var, 'Not set')

376

print(f" {var}: {value}")

377

378

# Platform info

379

print(f"\nPlatform: {sys.platform}")

380

print(f"Architecture: {machine()}")

381

382

# Java setup

383

try:

384

java_env = get_java_setup()

385

print(f"\nJava Setup:")

386

print(f" Java Home: {java_env.get_javahome()}")

387

print(f" Is JDK: {java_env.is_jdk()}")

388

print(f" Libraries: {java_env.get_libraries()}")

389

print(f" Library Dirs: {java_env.get_library_dirs()}")

390

print(f" Include Dirs: {java_env.get_include_dirs()}")

391

392

except Exception as e:

393

print(f"\nJava Setup Error: {e}")

394

395

# Usage

396

debug_java_environment()

397

```