Skip to content

Instantly share code, notes, and snippets.

@masthoon
Created February 10, 2018 16:14
Show Gist options
  • Save masthoon/8d324f77cf21312c177de06be57446ae to your computer and use it in GitHub Desktop.
Save masthoon/8d324f77cf21312c177de06be57446ae to your computer and use it in GitHub Desktop.
Launch a WSL process from Python (Windows)
import sys
import windows
import windows.winproxy
import windows.generated_def as gdef
# List distro: wslconfig /l
class WSLAPIProxy(windows.winproxy.ApiProxy):
APIDLL = "wslapi"
default_error_check = staticmethod(windows.winproxy.no_error_check)
"""
BOOL WINAPI WslIsDistributionRegistered(
PCWSTR distroName
);
"""
WslIsDistributionRegisteredPrototype = gdef.WINFUNCTYPE(gdef.BOOL, gdef.LPCWSTR)
WslIsDistributionRegisteredParams = ((1, 'distroName'),)
@WSLAPIProxy('WslIsDistributionRegistered', deffunc_module=sys.modules[__name__])
def WslIsDistributionRegistered(distroName):
return WslIsDistributionRegistered.ctypes_function(distroName)
"""
HRESULT WINAPI WslLaunch(
_In_ PCWSTR distroName,
_In_opt_ PCWSTR command,
_In_ BOOL useCurrentWorkingDirectory,
_In_ HANDLE hStdIn,
_In_ HANDLE hStdOut,
_In_ HANDLE hStdErr,
_Out_ HANDLE* phProcess
);
"""
WslLaunchPrototype = gdef.WINFUNCTYPE(gdef.BOOL, gdef.LPCWSTR, gdef.LPCWSTR, gdef.BOOL, gdef.HANDLE, gdef.HANDLE, gdef.HANDLE, gdef.PHANDLE)
WslLaunchParams = ((1, 'distroName'), (1, 'command'), (1, 'useCurrentWorkingDirectory'), (1, 'hStdIn'), (1, 'hStdOut'), (1, 'hStdErr'), (1, 'phProcess'))
@WSLAPIProxy('WslLaunch', deffunc_module=sys.modules[__name__])
def WslLaunch(distroName, command, useCurrentWorkingDirectory, hStdIn, hStdOut, hStdErr, phProcess):
return WslLaunch.ctypes_function(distroName, command, useCurrentWorkingDirectory, hStdIn, hStdOut, hStdErr, phProcess)
if __name__ == '__main__':
# Test distro
print("Legacy distro: {}".format(WslIsDistributionRegistered("Legacy")))
print("Ubuntu distro: {}".format(WslIsDistributionRegistered("Ubuntu")))
# Get std handles
stdin_handle = windows.winproxy.GetStdHandle(gdef.STD_INPUT_HANDLE)
stdout_handle = windows.winproxy.GetStdHandle(gdef.STD_OUTPUT_HANDLE)
stderr_handle = windows.winproxy.GetStdHandle(gdef.STD_ERROR_HANDLE)
# Launch proc
proc_handle = gdef.HANDLE()
WslLaunch("Legacy", "/usr/bin/python -c \"print(raw_input('Hello from Linux Python :)'))\"", True, stdin_handle, stdout_handle, stderr_handle, proc_handle)
proc = windows.winobject.process.WinProcess._from_handle(proc_handle.value)
print(proc)
proc.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment