Created
January 14, 2024 05:46
-
-
Save anonhostpi/30a1c958b4e5631f2080e3676a573922 to your computer and use it in GitHub Desktop.
Run Java in PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace Python.Runtime | |
# Install-Module Import-Package | Import-Module | |
Import-Package pythonnet | |
& { | |
$dll = Try { | |
where.exe python | ForEach-Object { | |
$root = $_ | Split-Path -Parent | |
$name = $root | Split-Path -Leaf | |
"$root\$name.dll" | |
} | Where-Object { Test-Path $_ } | Resolve-Path | |
} Catch { | |
[string] $promptedDll = $null | |
While( -not ([string]::IsNullOrEmpty( $promptedDll )) ){ | |
$promptedDll = Read-Host "Please provide a python to the python shared library (python.dll/python.so)" | |
} | |
$promptedDll | |
} | |
[Python.Runtime.Runtime]::PythonDLL = $dll | |
} | |
[Python.Runtime.PythonEngine]::Initialize() | Out-Null | |
[Python.Runtime.PythonEngine]::BeginAllowThreads() | Out-Null | |
New-Module -Name "CPython-GIL" -ScriptBlock { | |
$state = @{ "lock" = $null } | |
function global:Lock-Python { | |
Write-Host "Python GIL is now locked. Unlock it ANYTIME with Unlock-Python." -ForegroundColor Yellow | |
$state.lock = [Python.Runtime.Py]::GIL() | |
} | |
function global:Unlock-Python { | |
$state.lock.Dispose() | |
} | |
Export-ModuleMember | |
} | Import-Module | |
Lock-Python | |
$jpype = [py]::Import("jpype") | |
[py]::import("jpype.imports") | |
[py]::import("jpype.types") | |
$jpype.startJVM() | |
$system = $jpype.JPackage("java.lang").System | |
$system.out.println("Hello World from Java!") | |
$jpype.shutdownJVM() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment