def setup_i18n(i18nlang): global lang localedir = os.path.join( getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__))), "mo") if i18nlang is not None: os.environ["LANG"] = i18nlang lang = i18nlang else: lang, enc = locale.getdefaultlocale(("LANG", "LANGUAGE")) enc = "UTF-8" if sys.platform.startswith('win'): from ctypes import cdll, windll from ctypes.util import find_msvcrt putenv('LANG', lang) msvcrt = find_msvcrt() msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str( msvcrt) cdll.LoadLibrary(msvcrt)._putenv('LANG={}'.format(lang)) windll.kernel32.SetEnvironmentVariableW("LANG", lang) libintl = cdll.LoadLibrary("libintl-8.dll") libintl.bindtextdomain(APP, localedir) libintl.textdomain(APP) locale.setlocale(locale.LC_ALL, '') else: locale.setlocale(locale.LC_ALL, (lang, enc)) locale.bindtextdomain(APP, localedir) # print(f"Lang = ({lang}, {enc}) from {i18nlang} and LANG={os.environ['LANG']}") gettext.bindtextdomain(APP, localedir=localedir) gettext.textdomain(APP) if "_" in lang: lang = lang[:lang.find("_")].lower()
def _putenv(name, value): ''' :param name: environment variable name :param value: environment variable value This function ensures that changes to an environment variable are applied to each copy of the environment variables used by a process. Starting from Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) and are no longer automatically applied to the other copies for the process. On Microsoft Windows, each process has multiple copies of the environment variables, one managed by the OS and one managed by the C library. We also need to take care of the fact that the C library used by Python is not necessarily the same as the C library used by pygtk and friends. This because the latest releases of pygtk and friends are built with mingw32 and are thus linked against msvcrt.dll. The official gtk+ binaries have always been built in this way. ''' if sys.platform == 'win32' or sys.platform == 'nt': from ctypes import windll from ctypes import cdll from ctypes.util import find_msvcrt # Update Python's copy of the environment variables os.environ[name] = value # Update the copy maintained by Windows (so SysInternals Process Explorer sees it) try: result = windll.kernel32.SetEnvironmentVariableW(name, value) if result == 0: raise Warning except Exception: logger.debug('Failed to set environment variable \'%s\' (\'kernel32.SetEnvironmentVariableW\')' % name) else: logger.debug('Set environment variable \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')' % (name, value)) # Update the copy maintained by msvcrt (used by gtk+ runtime) try: result = cdll.msvcrt._putenv('%s=%s' % (name, value)) if result !=0: raise Warning except Exception: logger.debug('Failed to set environment variable \'%s\' (\'msvcrt._putenv\')' % name) else: logger.debug('Set environment variable \'%s\' to \'%s\' (\'msvcrt._putenv\')' % (name, value)) # Update the copy maintained by whatever c runtime is used by Python try: msvcrt = find_msvcrt() msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str(msvcrt) result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: logger.debug('Failed to set environment variable \'%s\' (\'%s._putenv\')' % (name, msvcrtname)) else: logger.debug('Set environment variable \'%s\' to \'%s\' (\'%s._putenv\')' % (name, value, msvcrtname))
def _make_is_append_mode(): # We build the platform-specific _is_append_mode function for Windows # inside a function factory in order to avoid cluttering the local # namespace with ctypes stuff from ctypes import (cdll, c_size_t, c_void_p, c_int, c_char, Structure, POINTER, cast) try: from ctypes.util import find_msvcrt except ImportError: # find_msvcrt is not available on Python 2.5 so we have to provide # it ourselves anyways from distutils.msvccompiler import get_build_version def find_msvcrt(): version = get_build_version() if version is None: # better be safe than sorry return None if version <= 6: clibname = 'msvcrt' else: clibname = 'msvcr%d' % (version * 10) # If python was built with in debug mode import imp if imp.get_suffixes()[0][0] == '_d.pyd': clibname += 'd' return clibname+'.dll' def _dummy_is_append_mode(fd): warnings.warn( 'Could not find appropriate MS Visual C Runtime ' 'library or library is corrupt/misconfigured; cannot ' 'determine whether your file object was opened in append ' 'mode. Please consider using a file object opened in write ' 'mode instead.') return False msvcrt_dll = find_msvcrt() if msvcrt_dll is None: # If for some reason the C runtime can't be located then we're dead # in the water. Just return a dummy function return _dummy_is_append_mode msvcrt = cdll.LoadLibrary(msvcrt_dll) # Constants IOINFO_L2E = 5 IOINFO_ARRAY_ELTS = 1 << IOINFO_L2E IOINFO_ARRAYS = 64 FAPPEND = 0x20 _NO_CONSOLE_FILENO = -2 # Types intptr_t = POINTER(c_int) class my_ioinfo(Structure): _fields_ = [('osfhnd', intptr_t), ('osfile', c_char)] # Functions _msize = msvcrt._msize _msize.argtypes = (c_void_p,) _msize.restype = c_size_t # Variables # Since we don't know how large the ioinfo struct is just treat the # __pioinfo array as an array of byte pointers __pioinfo = cast(msvcrt.__pioinfo, POINTER(POINTER(c_char))) # Determine size of the ioinfo struct; see the comment above where # _sizeof_ioinfo = None is set global _sizeof_ioinfo if __pioinfo[0] is not None: _sizeof_ioinfo = _msize(__pioinfo[0]) // IOINFO_ARRAY_ELTS if not _sizeof_ioinfo: # This shouldn't happen, but I suppose it could if one is using a # broken msvcrt, or just happened to have a dll of the same name # lying around. return _dummy_is_append_mode def _is_append_mode(fd): global _sizeof_ioinfo if fd != _NO_CONSOLE_FILENO: idx1 = fd >> IOINFO_L2E # The index into the __pioinfo array # The n-th ioinfo pointer in __pioinfo[idx1] idx2 = fd & ((1 << IOINFO_L2E) - 1) if 0 <= idx1 < IOINFO_ARRAYS and __pioinfo[idx1] is not None: # Doing pointer arithmetic in ctypes is irritating pio = c_void_p(cast(__pioinfo[idx1], c_void_p).value + idx2 * _sizeof_ioinfo) ioinfo = cast(pio, POINTER(my_ioinfo)).contents return bool(ord(ioinfo.osfile) & FAPPEND) return False return _is_append_mode
def _make_is_append_mode(): # We build the platform-specific _is_append_mode function for Windows # inside a function factory in order to avoid cluttering the local # namespace with ctypes stuff from ctypes import (cdll, c_size_t, c_void_p, c_int, c_char, Structure, POINTER, cast) try: from ctypes.util import find_msvcrt except ImportError: # find_msvcrt is not available on Python 2.5 so we have to provide # it ourselves anyways from distutils.msvccompiler import get_build_version def find_msvcrt(): version = get_build_version() if version is None: # better be safe than sorry return None if version <= 6: clibname = 'msvcrt' else: clibname = 'msvcr%d' % (version * 10) # If python was built with in debug mode import imp if imp.get_suffixes()[0][0] == '_d.pyd': clibname += 'd' return clibname + '.dll' def _dummy_is_append_mode(fd): warnings.warn( 'Could not find appropriate MS Visual C Runtime ' 'library or library is corrupt/misconfigured; cannot ' 'determine whether your file object was opened in append ' 'mode. Please consider using a file object opened in write ' 'mode instead.') return False msvcrt_dll = find_msvcrt() if msvcrt_dll is None: # If for some reason the C runtime can't be located then we're dead # in the water. Just return a dummy function return _dummy_is_append_mode msvcrt = cdll.LoadLibrary(msvcrt_dll) # Constants IOINFO_L2E = 5 IOINFO_ARRAY_ELTS = 1 << IOINFO_L2E IOINFO_ARRAYS = 64 FAPPEND = 0x20 _NO_CONSOLE_FILENO = -2 # Types intptr_t = POINTER(c_int) class my_ioinfo(Structure): _fields_ = [('osfhnd', intptr_t), ('osfile', c_char)] # Functions _msize = msvcrt._msize _msize.argtypes = (c_void_p, ) _msize.restype = c_size_t # Variables # Since we don't know how large the ioinfo struct is just treat the # __pioinfo array as an array of byte pointers __pioinfo = cast(msvcrt.__pioinfo, POINTER(POINTER(c_char))) # Determine size of the ioinfo struct; see the comment above where # _sizeof_ioinfo = None is set global _sizeof_ioinfo if __pioinfo[0] is not None: _sizeof_ioinfo = _msize(__pioinfo[0]) // IOINFO_ARRAY_ELTS if not _sizeof_ioinfo: # This shouldn't happen, but I suppose it could if one is using a # broken msvcrt, or just happened to have a dll of the same name # lying around. return _dummy_is_append_mode def _is_append_mode(fd): global _sizeof_ioinfo if fd != _NO_CONSOLE_FILENO: idx1 = fd >> IOINFO_L2E # The index into the __pioinfo array # The n-th ioinfo pointer in __pioinfo[idx1] idx2 = fd & ((1 << IOINFO_L2E) - 1) if 0 <= idx1 < IOINFO_ARRAYS and __pioinfo[idx1] is not None: # Doing pointer arithmetic in ctypes is irritating pio = c_void_p( cast(__pioinfo[idx1], c_void_p).value + idx2 * _sizeof_ioinfo) ioinfo = cast(pio, POINTER(my_ioinfo)).contents return bool(ord(ioinfo.osfile) & FAPPEND) return False return _is_append_mode
""" clock() function which works from within njit-ted code """ import ctypes import platform if platform.system() == 'Windows': from ctypes.util import find_msvcrt __LIB = find_msvcrt() if __LIB is None: __LIB = 'msvcrt.dll' else: from ctypes.util import find_library __LIB = find_library('c') clock = ctypes.CDLL(__LIB).clock clock.argtypes = []
# load the ADL 3.0 dso/dll _libadl = CDLL("libatiadlxx.so", mode=RTLD_GLOBAL) # ADL requires we pass an allocation function and handle freeing it ourselves _libc = CDLL("libc.so.6") else: from ctypes.util import find_msvcrt try: # first try to load the 64-bit library _libadl = CDLL("atiadlxx.dll") except OSError: # fall back on the 32-bit library _libadl = CDLL("atiadlxy.dll") _libc = CDLL(find_msvcrt()); _malloc = _libc.malloc _malloc.argtypes = [c_size_t] _malloc.restype = c_void_p _free = _libc.free _free.argtypes = [c_void_p] ADL_MAIN_MALLOC_CALLBACK = CFUNCTYPE(c_void_p, c_int) ADL_MAIN_FREE_CALLBACK = CFUNCTYPE(None, POINTER(c_void_p)) @ADL_MAIN_MALLOC_CALLBACK def ADL_Main_Memory_Alloc(iSize): return _malloc(iSize)
# -*- coding: utf-8 -*- import vimbastructure as structs from vimbaexception import VimbaException from sys import platform import os from ctypes import * if platform == "win32": from ctypes.util import find_msvcrt _cruntime = cdll.LoadLibrary(find_msvcrt()) vimbaC_path = r'C:\Program Files\Allied Vision Technologies\AVTVimba_1.2\VimbaC\Bin\Win32\VimbaC.dll' dll_loader = windll else: _cruntime = CDLL("libc.so.6") dll_loader = cdll assert os.environ.get("GENICAM_GENTL64_PATH"), "you need your GENICAM_GENTL64_PATH environment set. Make sure you have Vimba installed, and you have loaded the /etc/profile.d/ scripts" vimba_dir = "/".join(os.environ.get("GENICAM_GENTL64_PATH").split("/")[1:-3]) vimbaC_path = "/" + vimba_dir + "/VimbaC/DynamicLib/x86_64bit/libVimbaC.so" with open(vimbaC_path) as thefile: pass #NJO i think this is kind of like an os.exists ? class VimbaDLL(object): """ ctypes directives to make the wrapper class work cleanly, talks to VimbaC.dll """ # a full list of Vimba API methods # (only double dashed methods have been implemented so far) #
def _make_is_append_mode(): # We build the platform-specific _is_append_mode function for Windows # inside a function factory in order to avoid cluttering the local # namespace with ctypes stuff from ctypes import cdll, c_size_t, c_void_p, c_int, c_char, Structure, POINTER, cast from ctypes.util import find_msvcrt def _dummy_is_append_mode(fd): warnings.warn( "Could not find appropriate MS Visual C Runtime " "library or library is corrupt/misconfigured; cannot " "determine whether your file object was opened in append " "mode. Please consider using a file object opened in write " "mode instead." ) return False msvcrt_dll = find_msvcrt() if msvcrt_dll is None: # If for some reason the C runtime can't be located then we're dead # in the water. Just return a dummy function return _dummy_is_append_mode msvcrt = cdll.LoadLibrary(msvcrt_dll) # Constants IOINFO_L2E = 5 IOINFO_ARRAY_ELTS = 1 << IOINFO_L2E IOINFO_ARRAYS = 64 FAPPEND = 0x20 _NO_CONSOLE_FILENO = -2 # Types intptr_t = POINTER(c_int) class my_ioinfo(Structure): _fields_ = [("osfhnd", intptr_t), ("osfile", c_char)] # Functions _msize = msvcrt._msize _msize.argtypes = (c_void_p,) _msize.restype = c_size_t # Variables # Since we don't know how large the ioinfo struct is just treat the # __pioinfo array as an array of byte pointers __pioinfo = cast(msvcrt.__pioinfo, POINTER(POINTER(c_char))) # Determine size of the ioinfo struct; see the comment above where # _sizeof_ioinfo = None is set global _sizeof_ioinfo if __pioinfo[0] is not None: _sizeof_ioinfo = _msize(__pioinfo[0]) // IOINFO_ARRAY_ELTS if not _sizeof_ioinfo: # This shouldn't happen, but I suppose it could if one is using a # broken msvcrt, or just happened to have a dll of the same name # lying around. return _dummy_is_append_mode def _is_append_mode(fd): global _sizeof_ioinfo if fd != _NO_CONSOLE_FILENO: idx1 = fd >> IOINFO_L2E # The index into the __pioinfo array # The n-th ioinfo pointer in __pioinfo[idx1] idx2 = fd & ((1 << IOINFO_L2E) - 1) if 0 <= idx1 < IOINFO_ARRAYS and __pioinfo[idx1] is not None: # Doing pointer arithmetic in ctypes is irritating pio = c_void_p(cast(__pioinfo[idx1], c_void_p).value + idx2 * _sizeof_ioinfo) ioinfo = cast(pio, POINTER(my_ioinfo)).contents return bool(ord(ioinfo.osfile) & FAPPEND) return False return _is_append_mode
import numba import ctypes import platform if platform.system() == 'Windows': from ctypes.util import find_msvcrt lib = find_msvcrt() if lib is None: lib = 'msvcrt.dll' else: from ctypes.util import find_library lib = find_library('c') clock = ctypes.CDLL(lib).clock clock.argtypes = [] scale = 1 if platform.system() == 'Linux': scale = 1000 @numba.njit() def time(): value = clock() return value // scale
def _putenv(name, value): ''' :param name: environment variable name :param value: environment variable value This function ensures that changes to an environment variable are applied to each copy of the environment variables used by a process. Starting from Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) and are no longer automatically applied to the other copies for the process. On Microsoft Windows, each process has multiple copies of the environment variables, one managed by the OS and one managed by the C library. We also need to take care of the fact that the C library used by Python is not necessarily the same as the C library used by PyGTK and friends. This because the latest releases of PyGTK and friends are built with mingw32 and are thus linked against msvcrt.dll. The official GTK+ binaries have always been built in this way. ''' # Update Python's copy of the environment variables os.environ[name] = value # Update the copy maintained by Windows (so SysInternals Process Explorer sees it) try: result = windll.kernel32.SetEnvironmentVariableW(name, value) if result == 0: raise Warning except Exception: if sys.flags.verbose: sys.stderr.write( '* pygtk-runtime: "kernel32.SetEnvironmentVariableW" failed\n') sys.stderr.flush() else: if sys.flags.verbose: sys.stderr.write( '* pygtk-runtime: "kernel32.SetEnvironmentVariableW" successful\n' ) sys.stderr.flush() # Update the copy maintained by msvcrt (used by GTK+ runtime) try: result = cdll.msvcrt._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "msvcrt._putenv" failed\n') sys.stderr.flush() else: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "msvcrt._putenv" successful\n') sys.stderr.flush() # Update the copy maintained by whatever c runtime is used by Python try: msvcrt = find_msvcrt() msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str( msvcrt) result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "%s._putenv" failed\n' % msvcrtname) sys.stderr.flush() else: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "%s._putenv" successful\n' % msvcrtname) sys.stderr.flush()
def _putenv(name, value): ''' :param name: environment variable name :param value: environment variable value This function ensures that changes to an environment variable are applied to each copy of the environment variables used by a process. Starting from Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) and are no longer automatically applied to the other copies for the process. On Microsoft Windows, each process has multiple copies of the environment variables, one managed by the OS and one managed by the C library. We also need to take care of the fact that the C library used by Python is not necessarily the same as the C library used by PyGTK and friends. This because the latest releases of PyGTK and friends are built with mingw32 and are thus linked against msvcrt.dll. The official GTK+ binaries have always been built in this way. ''' # Update Python's copy of the environment variables os.environ[name] = value # Update the copy maintained by Windows (so SysInternals Process Explorer sees it) try: result = windll.kernel32.SetEnvironmentVariableW(name, value) if result == 0: raise Warning except Exception: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "kernel32.SetEnvironmentVariableW" failed\n') sys.stderr.flush() else: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "kernel32.SetEnvironmentVariableW" successful\n') sys.stderr.flush() # Update the copy maintained by msvcrt (used by GTK+ runtime) try: result = cdll.msvcrt._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "msvcrt._putenv" failed\n') sys.stderr.flush() else: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "msvcrt._putenv" successful\n') sys.stderr.flush() # Update the copy maintained by whatever c runtime is used by Python try: msvcrt = find_msvcrt() msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str(msvcrt) result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "%s._putenv" failed\n' % msvcrtname) sys.stderr.flush() else: if sys.flags.verbose: sys.stderr.write('* pygtk-runtime: "%s._putenv" successful\n' % msvcrtname) sys.stderr.flush()
mydir = os.path.abspath(os.path.dirname(__file__)) if mydir.lower() not in [p.lower() for p in sys.path]: sys.path.insert(0, mydir) if is_x64: print 'This script requires an 32-bit version of Python.\n' print 'If you have a 32-bit version of Python, but dont want to have to add it to your PATH, add a bat file to your PATH called, "x86env.bat" or "x86env.cmd" that temporarily adds it to your PATH.\n' print 'Something like:' print '@set PATH=%%PATH:\\mypythonx64folder\\=\\mypythonx86folder\\%%\n' sys.exit(1) if is_pypy: handle = GetModuleHandleW('libpypy-c.dll') else: handle = sys.dllhandle rkernel32 = RWinDLL(util.find_library('kernel32')) if not is_pypy: smsvcrt = util.find_library(util.find_msvcrt()) if smsvcrt is None: smsvcrt = util.find_library('msvcr100') msvcrt = RCDLL(smsvcrt) pyhome = os.path.abspath(os.path.dirname(sys.executable)) pypath = ';'.join(sys.path) path = 'PATH=%s' % (pyhome + ';' + os.environ['PATH']).replace(';;',';') putenv = msvcrt._putenv putenv.argtypes = [ c_char_p ] putenv.restype = c_int putenv(path) putenv('PYTHONPATH=%s' % pypath) python = RCDLL(handle=handle) pytab.populate_exports(python) python.Py_SetProgramName(sys.executable)
mydir = os.path.abspath(os.path.dirname(__file__)) if mydir.lower() not in [p.lower() for p in sys.path]: sys.path.insert(0, mydir) if is_x64: print 'This script requires an 32-bit version of Python.\n' print 'If you have a 32-bit version of Python, but dont want to have to add it to your PATH, add a bat file to your PATH called, "x86env.bat" or "x86env.cmd" that temporarily adds it to your PATH.\n' print 'Something like:' print '@set PATH=%%PATH:\\mypythonx64folder\\=\\mypythonx86folder\\%%\n' sys.exit(1) if is_pypy: handle = GetModuleHandleW('libpypy-c.dll') else: handle = sys.dllhandle rkernel32 = RWinDLL(util.find_library('kernel32')) if not is_pypy: smsvcrt = util.find_library(util.find_msvcrt()) if smsvcrt is None: smsvcrt = util.find_library('msvcr100') msvcrt = RCDLL(smsvcrt) pyhome = os.path.abspath(os.path.dirname(sys.executable)) pypath = ';'.join(sys.path) path = 'PATH=%s' % (pyhome + ';' + os.environ['PATH']).replace( ';;', ';') putenv = msvcrt._putenv putenv.argtypes = [c_char_p] putenv.restype = c_int putenv(path) putenv('PYTHONPATH=%s' % pypath) python = RCDLL(handle=handle) pytab.populate_exports(python)
if sys_plat == "win32": def find_win_dll(arch): """ Finds the highest versioned windows dll for the specified architecture. """ base = r'C:\Program Files\Allied Vision Technologies\AVTVimba_1.%i\VimbaC\Bin\Win%i\VimbaC.dll' dlls = [ base % (i, arch) for i in range(10) if os.path.isfile(base % (i, arch)) ] if not dlls: raise IOError("VimbaC.dll not found.") return dlls[-1] from ctypes.util import find_msvcrt _cruntime = cdll.LoadLibrary(find_msvcrt()) if '64' in platform.architecture()[0]: vimbaC_path = find_win_dll(64) else: vimbaC_path = find_win_dll(32) dll_loader = windll else: _cruntime = CDLL("libc.so.6") dll_loader = cdll assert os.environ.get( "GENICAM_GENTL64_PATH" ), "you need your GENICAM_GENTL64_PATH environment set. Make sure you have Vimba installed, and you have loaded the /etc/profile.d/ scripts" vimba_dir = "/".join( os.environ.get("GENICAM_GENTL64_PATH").split("/")[1:-3]) vimbaC_path = "/" + vimba_dir + "/VimbaC/DynamicLib/x86_64bit/libVimbaC.so"
def set_env_variable(name, value): """ :param name: environment variable name :param value: environment variable value This function ensures that changes to an environment variable are applied to each copy of the environment variables used by a process. Starting from Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) and are no longer automatically applied to the other copies for the process. On Microsoft Windows, each process has multiple copies of the environment variables, one managed by the OS and one managed by the C library. We also need to take care of the fact that the C library used by Python is not necessarily the same as the C library used by pygtk and friends. This because the latest releases of pygtk and friends are built with mingw32 and are thus linked against msvcrt.dll. The official gtk+ binaries have always been built in this way. Basen on _putenv in TransUtils.py from sourceforge project gramps http://sourceforge.net/p/gramps/code/HEAD/tree/branches/maintenance/gramps32/src/TransUtils.py """ # Update Python's copy of the environment variables try: os.environ[name] = value except UnicodeEncodeError: # Python 2 os.environ[name] = value.encode('utf8') if windows_check(): from ctypes import windll from ctypes import cdll from ctypes.util import find_msvcrt # Update the copy maintained by Windows (so SysInternals Process Explorer sees it) try: result = windll.kernel32.SetEnvironmentVariableW(name, value) if result == 0: raise Warning except Exception: log.warning('Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name) else: log.debug('Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name, value) # Update the copy maintained by msvcrt (used by gtk+ runtime) try: result = cdll.msvcrt._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')', name) else: log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')', name, value) # Update the copy maintained by whatever c runtime is used by Python try: msvcrt = find_msvcrt() msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str(msvcrt) result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: log.warning('Failed to set Env Var \'%s\' (\'%s._putenv\')', name, msvcrtname) else: log.debug('Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')', name, value, msvcrtname)
def set_env_variable(name, value): """ :param name: environment variable name :param value: environment variable value This function ensures that changes to an environment variable are applied to each copy of the environment variables used by a process. Starting from Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) and are no longer automatically applied to the other copies for the process. On Microsoft Windows, each process has multiple copies of the environment variables, one managed by the OS and one managed by the C library. We also need to take care of the fact that the C library used by Python is not necessarily the same as the C library used by pygtk and friends. This because the latest releases of pygtk and friends are built with mingw32 and are thus linked against msvcrt.dll. The official gtk+ binaries have always been built in this way. Basen on _putenv in TransUtils.py from sourceforge project gramps http://sourceforge.net/p/gramps/code/HEAD/tree/branches/maintenance/gramps32/src/TransUtils.py """ # Update Python's copy of the environment variables try: os.environ[name] = value except UnicodeEncodeError: # Python 2 os.environ[name] = value.encode('utf8') if windows_check(): from ctypes import windll from ctypes import cdll from ctypes.util import find_msvcrt # Update the copy maintained by Windows (so SysInternals Process Explorer sees it) try: result = windll.kernel32.SetEnvironmentVariableW(name, value) if result == 0: raise Warning except Exception: log.warning( 'Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name, ) else: log.debug( 'Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name, value, ) # Update the copy maintained by msvcrt (used by gtk+ runtime) try: result = cdll.msvcrt._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')', name) else: log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')', name, value) # Update the copy maintained by whatever c runtime is used by Python try: msvcrt = find_msvcrt() msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str( msvcrt) result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value)) if result != 0: raise Warning except Exception: log.warning('Failed to set Env Var \'%s\' (\'%s._putenv\')', name, msvcrtname) else: log.debug('Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')', name, value, msvcrtname)
suffix += '|XL' for key, value in vars(_xltypes).iteritems(): if key.startswith('xltype') and value == _xltype: return key + suffix return "0x{:04X}".format(_xltype) + suffix def _malloc_errcheck(result, _, __): """capture 0 pointers from malloc and convert to exceptions""" if result == None: raise MemoryError('malloc: failed to allocate memory') return result _crt = ctypes.CDLL(find_msvcrt()) _malloc = CFUNCTYPE(c_void_p, c_size_t)(('malloc', _crt)) _malloc.errcheck = _malloc_errcheck _free = CFUNCTYPE(None, c_void_p)(('free', _crt)) def _colref(col): """convert column number to column letter""" div, mod = divmod(col, 26) return chr(ord('A') + mod) if div == 0 else _colref(div) + _colref(mod) class _XLOPER(object): def __init__(self, value=None): # pylint: disable=W0231 self._set(value)