def _get_windows_lib(cls, library_path): from ctypes import windll try: if sys.version_info[:3] == (2, 7, 13): # http://bugs.python.org/issue29082 library_path = str(library_path) lib = windll.MediaInfo = windll.LoadLibrary(library_path) return cls._initialize_lib(lib) except OSError: pass
def printError(codigo): # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad( 9600 ) Handle_HL.ConfigurarPuerto( PUERTO ) error = Handle_HL.Conectar() response = create_string_buffer( b'\000' * 200 ) error = Handle_HL.ConsultarDescripcionDeError(int(codigo),response,200) return str(response.value)
def login(self): _LOGGING.info("start login...") self.driver.maximize_window() # 禁用鼠标和键盘 user32 = windll.LoadLibrary('user32.dll') user32.BlockInput(True) _LOGGING.info("block input start...") try: _LOGGING.info("open the window...") self.driver.get(self.url[0]) time.sleep(1) WebDriverWait(self.driver, 120).until(lambda driver: driver.execute_script( "return document.readyState") == 'complete') if not self.driver.find_elements_by_id('gw-lefty'): self.login_str() _LOGGING.info("login successfully!") self.driver.maximize_window() # login successful self.log_result_flag = True errmsg = '' # log into db self.log_to_db(self.sys_username, self.mac, 'login...', 'success', errmsg) _LOGGING.info("monitoring, exit system when all windows closed") # exit system when all windows closed user32.BlockInput(False) while True: time.sleep(1) winhandles = self.driver.window_handles if len(winhandles) == 0: self.deleteAll() except Exception as e: if self.log_result_flag: errmsg = str(e) _LOGGING.error(errmsg) # log into db self.log_to_db(self.sys_username, self.mac, 'Chrome closed', 'System exit', errmsg) else: errmsg = str(e) _LOGGING.error(errmsg) # log into db self.log_to_db(self.sys_username, self.mac, 'loginUrls', 'failed_2', errmsg) _LOGGING.error( "--------------------------------error-------------------------" ) _LOGGING.error(e) _LOGGING.error( "--------------------------------error-------------------------" ) finally: user32.BlockInput(False) self.deleteAll()
def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}): """Retrieve a function from a library, and set the data types.""" from ctypes import windll if libname not in _libcache: _libcache[libname] = windll.LoadLibrary(libname) func = getattr(_libcache[libname], funcname) func.argtypes = argtypes func.restype = restype return func
def __init__(self, vBaseAddr=0x378): 'Init LPT Port, default base address: 0x378' self._vLptBaseAddr = vBaseAddr # try to load Parallel Port dll try: self._inpout32 = windll.LoadLibrary('inpout32.dll') except: self._assert('Load "inpout32.dll" fail!') self._vLptOut = 0xFF
def __init__(self, dllPath="./F3API.dll", logPre=">"): """ 载入dll :param dllPath: """ self.sessionId = None self.logPre = logPre if os.path.exists(dllPath): self.dllObj = windll.LoadLibrary(dllPath) consoleLog(self.logPre, "已载入", dllPath) else: consoleLog(self.logPre, "载入[", dllPath, "]失败,文件不存在")
def __init__(self, serialNumber=None, connect=True): """ Load DLLs. """ if platform.system() == 'Linux': from ctypes import cdll # ok I don't know what is wrong with my installer, but I need to include # .so.2 self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".so.2") else: from ctypes import windll self.lib = windll.LoadLibrary(self.LIBNAME + ".dll") super(PS6000, self).__init__(serialNumber, connect)
def _link_library(self, lib_path, convention): """Find and link the external librairy if only a path was provided. """ if convention == 'cdll': return cdll.LoadLibrary(lib_path) elif convention == 'windll': return windll.LoadLibrary(lib_path) elif convention == 'oledll': return oledll.LoadLibrary(lib_path) else: raise ValueError('Convention cannot be {}'.format(convention))
def __init__(self, channel, status): CH341Handler.__init__(self, channel=channel, status=status) try: self.driver = windll.LoadLibrary("CH341DLL.dll") except FileNotFoundError as e: self.channel("%s: %s" % (str(type(e)), str(e))) raise ImportError( "FileNotFoundError for misconfigured CH341DLL.dll. See Issue #459" ) except (NameError, OSError) as e: self.channel(str(e)) raise ConnectionRefusedError
def __init__(self, serialNumber=None, connect=True): """Load DLL etc""" if platform.system() == 'Linux': from ctypes import cdll self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".so") else: from ctypes import windll self.lib = windll.LoadLibrary(self.LIBNAME + ".dll") self.resolution = self.ADC_RESOLUTIONS["8"] super(PS5000a, self).__init__(serialNumber, connect)
def ticket_debit_note_B(): #title print "*** TICKET DEBIT NOTE 'B' ***" # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad( 9600 ) Handle_HL.ConfigurarPuerto( PUERTO ) error = Handle_HL.Conectar() print "Connect : ", print printError(error) # try cancel error = Handle_HL.Cancelar() print "Cancel : ", print printError(error) # load customer data error = Handle_HL.CargarDatosCliente( "Nombre Comprador #1", "Nombre Comprador #2", "Domicilio Comprador #1", "Domicilio Comprador #2", "Domicilio Comprador #3", ID_TIPO_DOCUMENTO_CUIT, "24272242549", ID_RESPONSABILIDAD_IVA_MONOTRIBUTISTA ) print "Customer Data : ", print printError(error) # load customer data error = Handle_HL.CargarComprobanteAsociado( "083-00001-00000027" ) print "Customer Remit #1 : ", print printError(error) # load customer data error = Handle_HL.CargarComprobanteAsociado( "082-00003-01003020" ) print "Customer Remit #2 : ", print printError(error) # open error = Handle_HL.AbrirComprobante( ID_TIPO_COMPROBANTE_TIQUE_NOTA_DE_DEBITO ) print "Open : ", print printError(error) # fixed info send_fixed_invoice_body( Handle_HL ) # close error = Handle_HL.CerrarComprobante() print "Close : ", print printError(error) # disconect error = Handle_HL.Desconectar() print "Disconect : ", print printError(error)
def __init__(self, max_threads=0): if platform.system() == "Windows": libname = "libdds.dll" elif platform.system() == "Darwin": libname = "libdds.2.dylib" else: libname = "libdds.so.2" if os.path.exists(LIBDDSPATH + libname): libname = LIBDDSPATH + libname self.libdds = libloader.LoadLibrary(libname) self.libdds.SetMaxThreads(max_threads)
def init(self, dllType=None, mode=None): #使用的dll 初始化加载相应的dll if not dllType: self.dll_path = self.BASE_DIR + "JLAPI.dll" self.dll = windll.LoadLibrary(self.dll_path) #外后回加载相应其他类型dll else: pass if mode: self.mode = mode return True
def __init__(self, serialNumber=None, connect=True): """Load DLL etc""" if platform.system() == 'Linux': from ctypes import cdll self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".so") elif platform.system() == 'Darwin': from ctypes import cdll self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".dylib") else: from ctypes import windll self.lib = windll.LoadLibrary(self.LIBNAME + ".dll") super(PS2000, self).__init__(serialNumber, connect)
def __init__(self, lib_location=None): if self.cdll: return self.lib_location = lib_location or self.lib_location or find_library( 'snap7') if not self.lib_location: msg = "can't find snap7 library. If installed, try running ldconfig" self.lib_location = GetSnap7Dll() print self.lib_location #print self.lib_location if not os.path.isfile(self.lib_location): raise Snap7Exception(msg) self.cdll = cdll.LoadLibrary(self.lib_location)
def __init__(self, stage='M521DG', com_port='COM1', baud_rate=9600): if stage not in self.stages.keys(): raise Exception('not valid stage') if com_port not in self.aliases: raise IOError('invalid com port') if baud_rate not in self.baudrates: raise IOError('invalid baudrate') self.stage = stage super(MMC_Wrapper, self).__init__() self._comport = com_port self._baudrate = baud_rate self._dll = windll.LoadLibrary( os.path.join(os.path.split(__file__)[0], 'MMC.dll'))
def __init__(self): self.pixci_opened = False self.bit_depth = None self.roi_shape = None self.camera = None self.exposure = None self.roi_pos = None self.frametime = None try: from ctypes import c_ubyte, windll, sizeof, c_ushort except ImportError: raise CameraOpenError("Import failed") self.epix = windll.LoadLibrary("C:\Program Files\EPIX\XCLIB\XCLIBW64.dll")
def _create_native_lib(): os_family = 'windows' if (os.name in ('nt', 'dos', 'os2', 'ce')) else ( 'macos' if sys.platform == "darwin" else 'unix') logger.debug('Detected os family: %s', os_family) try: if os_family == 'unix': from ctypes import CDLL logger.debug('Loading native mediainfo library') so_name = 'libmediainfo.so.0' for location in ('/usr/local/mediainfo/lib', ): candidate = os.path.join(location, so_name) if os.path.isfile(candidate): so_name = candidate break lib = CDLL(so_name) else: # pragma: no cover os_folder = os.path.abspath( os.path.join(os.path.dirname(__file__), '../native', os_family)) if os_family == 'macos': from ctypes import CDLL logger.debug('Loading native mediainfo library from %s', os_folder) lib = CDLL(os.path.join(os_folder, 'libmediainfo.0.dylib')) else: from ctypes import windll is_64bits = sys.maxsize > 2**32 arch = 'x86_64' if is_64bits else 'i386' lib = os.path.join(os_folder, arch) logger.debug('Loading native mediainfo library from %s', lib) lib = windll.MediaInfo = windll.LoadLibrary( os.path.join(lib, 'MediaInfo.dll')) lib.MediaInfo_Inform.restype = c_wchar_p lib.MediaInfo_New.argtypes = [] lib.MediaInfo_New.restype = c_void_p lib.MediaInfo_Option.argtypes = [c_void_p, c_wchar_p, c_wchar_p] lib.MediaInfo_Option.restype = c_wchar_p lib.MediaInfo_Inform.argtypes = [c_void_p, c_size_t] lib.MediaInfo_Inform.restype = c_wchar_p lib.MediaInfo_Open.argtypes = [c_void_p, c_wchar_p] lib.MediaInfo_Open.restype = c_size_t lib.MediaInfo_Delete.argtypes = [c_void_p] lib.MediaInfo_Delete.restype = None lib.MediaInfo_Close.argtypes = [c_void_p] lib.MediaInfo_Close.restype = None logger.debug('MediaInfo loaded') return lib except OSError: logger.warning('Unable to load native mediainfo library')
def compare_cache_bio_emp(tmp): try: mathpro = windll.LoadLibrary("match.dll") send_tmp = create_string_buffer(tmp.decode()) cache_bio = get_all_bio_from_cache() print 'cache_bio:', len(cache_bio) for e in cache_bio: user_tep = create_string_buffer(e[0]) math_result = mathpro.process10(user_tep, send_tmp) if math_result == FP_IDENTIFY_SUCCESS: return e[1] except: return None return None
def exitproc(): log("exitproc", os.name) if os.name == "posix": pass #dont't need, but just for now ... #import signal #os.kill(os.getpid(), signal.SIGKILL) elif os.name == "nt": #runtime error if smpeg imported ... from ctypes import windll kernel32 = windll.LoadLibrary("kernel32.dll") process = kernel32.OpenProcess(1, False, os.getpid()) if process: kernel32.TerminateProcess(process, 0) os._exit(0) #no thread and __del__ error message
def ticket_credit_note(comprobante,tipoComprobante,items): #title print "*** TICKET CREDIT NOTE ***" # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad( 9600 ) Handle_HL.ConfigurarPuerto( PUERTO ) error = Handle_HL.Conectar() print "Connect : ", print printError(error) # try cancel error = Handle_HL.Cancelar() print "Cancel : ", print printError(error) # load customer data error = Handle_HL.CargarDatosCliente( "CONSUMIDOR FINAL", " ", " ", " ", " ", ID_TIPO_DOCUMENTO_NINGUNO, "24272242549", ID_RESPONSABILIDAD_IVA_CONSUMIDOR_FINAL ) print "Customer Data : ", print printError(error) # load customer data error = Handle_HL.CargarComprobanteAsociado( str(comprobante) ) print "main source voucher : ", print printError(error) # open error = Handle_HL.AbrirComprobante( int(tipoComprobante) ) print "Open : ", print printError(error) # fixed info send_fixed_invoice_body( Handle_HL , items ) # close error = Handle_HL.CerrarComprobante() print "Close : ", print printError(error) # disconect error = Handle_HL.Desconectar() print "Disconect : ", print printError(error) return { "status" : True , "tipo" : "tique nota de credito" }
def set_and_get_header_trailer(): #title print "*** HEADER & TRAILER ***" # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad( 9600 ) Handle_HL.ConfigurarPuerto( PUERTO ) error = Handle_HL.Conectar() print "Connect : ", print printError(error) # set header #1 error = Handle_HL.EstablecerEncabezado( 1, "" ) print "Config Header Error : ", print printError(error) # get header #1 str_header1_max_len = 100 str_header1 = create_string_buffer( b'\000' * str_header1_max_len ) error = Handle_HL.ConsultarEncabezado( 1, str_header1, str_header1_max_len ) print "Get Header Error : ", print printError(error) print "Header #1 String : ", print str_header1.value # set trailer #1 error = Handle_HL.EstablecerCola( 1, "" ) print "Config Trailer Error : ", print printError(error) # get trailer #1 str_trailer1_max_len = 100 str_trailer1 = create_string_buffer( b'\000' * str_trailer1_max_len ) error = Handle_HL.ConsultarCola( 1, str_trailer1, str_trailer1_max_len ) print "Get Trailer Error : ", print printError(error) print "Trailer #1 String : ", print str_trailer1.value # close port error = Handle_HL.Desconectar() print "Disconect : ", print printError(error)
def cancel_all(): #title print "*** CANCEL ALL ***" # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad(9600) Handle_HL.ConfigurarPuerto("0") error = Handle_HL.Conectar() print "Connect : ", print error # get document number str_doc_number_max_len = 20 str_doc_number = create_string_buffer(b'\000' * str_doc_number_max_len) error = Handle_HL.ConsultarNumeroComprobanteActual(str_doc_number, str_doc_number_max_len) print "Get Doc. Number Error : ", print error print "Doc Number : ", print str_doc_number.value # get document type str_doc_type_max_len = 20 str_doc_type = create_string_buffer(b'\000' * str_doc_type_max_len) error = Handle_HL.ConsultarTipoComprobanteActual(str_doc_type, str_doc_type_max_len) print "Get Type Doc. Error : ", print error print "Doc Type : ", print str_doc_type.value # try cancel error = Handle_HL.Cancelar() print "Cancel : ", print error # get last error error = Handle_HL.ConsultarUltimoError() print "Last Error : ", print error # close port error = Handle_HL.Desconectar() print "Disconect : ", print error
def ticket_invoice_B(nombreComprador,descuento,tipoDocumento,documento,tipoResponsable,items): #title print "*** TICKET INVOICE 'B' ***" # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad( 9600 ) Handle_HL.ConfigurarPuerto( "0" ) error = Handle_HL.Conectar() print "Connect : ", print printError(error) # cancel error = Handle_HL.Cancelar() print "Cancel : ", print printError(error) # load customer data error = Handle_HL.CargarDatosCliente( str(nombreComprador), " ", " ", " ", " ", int(tipoDocumento), str(documento), ID_RESPONSABILIDAD_IVA_MONOTRIBUTISTA ) print "Customer Data : ", print printError(error) # open error = Handle_HL.AbrirComprobante( ID_TIPO_COMPROBANTE_TIQUE_FACTURA ) print "Open : ", print printError(error) # fixed info send_fixed_invoice_body( Handle_HL,items ) # global discount error = Handle_HL.CargarAjuste( ID_MODIFICADOR_DESCUENTO, "Descuento", str(descuento), 0, "CodigoInterno4567890123456789012345678901234567890" ) print "Discount : ", print printError(error) # close error = Handle_HL.CerrarComprobante() print "Close : ", print printError(error) # disconect error = Handle_HL.Desconectar() print "Disconect : ", print printError(error)
def loadlib(self, fullpath_dll): pre = fullpath_dll # This is good fullpath_dll = io_out_arg(fullpath_dll, pfn_check=os.path.exists) # win32:TypeError: LoadLibrary() argument 1 must be string, not unicode # linux: UnicodeEncodeError: 'ascii' codec can't encode characters in position 47-48: ordinal not in range(128) io_print(u'ctypes lib load ({0}){1}'.format(type(fullpath_dll), pre)) lib = library_loader.LoadLibrary(fullpath_dll) if not lib: raise ValueError('fail load') hr = lib.InitExportFunctions(pointer(self)) assert hr == 0 return (hr, 0)
def __init__(self, serialNumber=None, connect=True): """Load DLLs.""" if platform.system() == 'Linux': from ctypes import cdll # ok I don't know what is wrong with my installer, # but I need to include .so.2 self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".so.2") elif platform.system() == 'Darwin': from picoscope.darwin_utils import LoadLibraryDarwin self.lib = LoadLibraryDarwin("lib" + self.LIBNAME + ".dylib") else: from ctypes import windll self.lib = windll.LoadLibrary(str(self.LIBNAME + ".dll")) super(PS5000, self).__init__(serialNumber, connect)
def __init__(self, serialNumber=None, connect=True): """Load DLL etc.""" if platform.system() == 'Linux': from ctypes import cdll self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".so") elif platform.system() == 'Darwin': from picoscope.darwin_utils import LoadLibraryDarwin self.lib = LoadLibraryDarwin("lib" + self.LIBNAME + ".dylib") else: from ctypes import windll from ctypes.util import find_library self.lib = windll.LoadLibrary( find_library(str(self.LIBNAME + ".dll"))) super(PS2000, self).__init__(serialNumber, connect)
def __init__(self, serialNumber=None, connect=True): """Load DLL etc.""" if platform.system() == 'Linux': from ctypes import cdll self.lib = cdll.LoadLibrary("lib" + self.LIBNAME + ".so") elif platform.system() == 'Darwin': from picoscope.darwin_utils import LoadLibraryDarwin self.lib = LoadLibraryDarwin("lib" + self.LIBNAME + ".dylib") else: from ctypes import windll self.lib = windll.LoadLibrary(str(self.LIBNAME + ".dll")) self.resolution = self.ADC_RESOLUTIONS["8"] super(PS3000a, self).__init__(serialNumber, connect)
def descarga(desde,hasta): #title print "*** DESCARGANDO ARCHIVOS AFIP ***" # get handle from DLL Handle_HL = windll.LoadLibrary("EpsonFiscalInterface.dll") # connect Handle_HL.ConfigurarVelocidad( 9600 ) Handle_HL.ConfigurarPuerto( PUERTO ) error = Handle_HL.Conectar() print "Connect : ", print printError(error) # try cancel vouchers error = Handle_HL.Cancelar() print "Cancel voucher : ", print printError(error) # download carpeta_de_descarga = "donwloads" error = Handle_HL.Descargar(str(desde), str(hasta),CARPETA_DESTINO.replace("\\","/")) print "Download : ", resultado = printError(error) print resultado print error mensaje = "" if error == 2055: mensaje = "PERIODO AUDITADO SIN DATOS. VERIFIQUE EL RANGO DE FECHAS" elif error == 2071: mensaje = "FALTA DESCARGAR JORNADAS PREVIAS. REALICE UNA DESCARGAGA PENDIENTE" else: mensaje = "REPORTES DESCARGADOS" abrirCarpeta() # disconect error = Handle_HL.Desconectar() print "Disconect : ", print printError(error) return { "resultado" : mensaje }
def __init__(self, *args, **kwargs): """ initialize the Netica class """ if not os.path.exists(NETICA_LIB): # library Netica.dll or libnetica.so not found err = exceptions.RuntimeError('"%s" NOT FOUND at\n %s' %(os.path.split(NETICA_LIB)[-1], NETICA_LIB)) logger.error(err) raise err #self.ln = windll.LoadLibrary(NETICA_LIB) #TODO: use cdll if 'window' in platform.system().lower(): self.ln = windll.LoadLibrary(NETICA_LIB) else: self.ln = cdll.LoadLibrary(NETICA_LIB)