| 1 |
|
| 2 |
|
| 3 |
class CFFIWrapper(object): |
| 4 |
def __init__(self): |
| 5 |
import cffi |
| 6 |
ffi = cffi.FFI() |
| 7 |
ffi.cdef(""" |
| 8 |
HINSTANCE ShellExecuteA(HWND, LPCSTR, LPCSTR, LPCSTR, LPCSTR, INT); |
| 9 |
HINSTANCE ShellExecuteW(HWND, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, INT); |
| 10 |
""") |
| 11 |
self.NULL = ffi.NULL |
| 12 |
self.cast = ffi.cast |
| 13 |
self.lib = ffi.dlopen("Shell32.dll") |
| 14 |
self.SW_SHOWNORMAL = 1 |
| 15 |
self.getwinerror = ffi.getwinerror |
| 16 |
|
| 17 |
_cffi_wrapper = None |
| 18 |
|
| 19 |
|
| 20 |
def startfile(filepath, operation=None): |
| 21 |
global _cffi_wrapper |
| 22 |
if _cffi_wrapper is None: |
| 23 |
_cffi_wrapper = CFFIWrapper() |
| 24 |
w = _cffi_wrapper |
| 25 |
|
| 26 |
if operation is None: |
| 27 |
operation = w.NULL |
| 28 |
if isinstance(filepath, bytes): |
| 29 |
if isinstance(operation, str): |
| 30 |
operation = operation.encode("ascii") |
| 31 |
rc = w.lib.ShellExecuteA(w.NULL, operation, filepath, |
| 32 |
w.NULL, w.NULL, w.SW_SHOWNORMAL) |
| 33 |
elif isinstance(filepath, str): |
| 34 |
if isinstance(operation, bytes): |
| 35 |
operation = operation.decode("ascii") |
| 36 |
rc = w.lib.ShellExecuteW(w.NULL, operation, filepath, |
| 37 |
w.NULL, w.NULL, w.SW_SHOWNORMAL) |
| 38 |
else: |
| 39 |
raise TypeError("argument 1 must be str or bytes") |
| 40 |
rc = int(w.cast("uintptr_t", rc)) |
| 41 |
if rc <= 32: |
| 42 |
code, msg = w.getwinerror() |
| 43 |
raise WindowsError(code, msg, filepath) |