示例#1
0
文件: mover.py 项目: mdengler/mover
def get_titlebar_size(windowHandle):
    tbi = TITLEBARINFO()
    #tbi.cbSize = ctypes.sizeof(TITLEBARINFO)
    user.GetTitleBarInfo(windowHandle, byref(tbi))
    win32api.FormatMessage(win32api.GetLastError())

    return (tbi.rcTitleBar.b.x - tbi.rcTitleBar.a.x,
            tbi.rcTitleBar.b.y - tbi.rcTitleBar.a.y)
示例#2
0
 def acquire(self, timeout=None):
     '''
     Acquire ownership of the mutex. If a
     timeout is specified, it will wait a maximum of timeout seconds to
     acquire the mutex. On an acquire timeout condition, will raise
     NamedMutexTimeoutException. Raises IOError on other errors.
     '''
     if is_windows():
         if timeout is None:
             # Wait forever (INFINITE)
             win_timeout = 0xFFFFFFFF
         else:
             win_timeout = int(round(timeout * 1000))
         ret = win32event.WaitForSingleObject(self.handle, win_timeout)  # pylint: disable=no-member
         if ret in (0, 0x80):
             # Note that this doesn't distinguish between normally acquired (0)
             # and acquired due to another owning process terminating without
             # releasing (0x80)
             pass
         elif ret == 0x102:
             # Timeout
             raise NamedMutexTimeoutException(
                 'Failed to acquire named mutex "{0}" due to timeout'.
                 format(self.name))
         else:
             # Acquire failed
             raise IOError(
                 'Failed to acquire named mutex "{0}". Error code: {1}'.
                 format(
                     self.name,
                     win32api.GetLastError()  # pylint: disable=no-member
                 ))
     else:
         if timeout is None:
             # Wait forever (INFINITE)
             fcntl.flock(self.handle, fcntl.LOCK_EX)
         elif timeout == 0:
             try:
                 fcntl.flock(self.handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
             except IOError as exc:
                 if exc.errno == errno.EWOULDBLOCK:
                     raise NamedMutexTimeoutException(
                         'Failed to acquire named mutex "{0}" due to timeout'
                         .format(self.name))
                 else:
                     raise
         else:
             with _timeout_context(timeout):
                 try:
                     fcntl.flock(self.handle, fcntl.LOCK_EX)
                 except IOError as exc:
                     if exc.errno == errno.EINTR:
                         raise NamedMutexTimeoutException(
                             'Failed to acquire named mutex "{0}" due to timeout'
                             .format(self.name))
                     else:
                         raise
     self.acquired = True
示例#3
0
def rdt_client():

    print("rdt: client begin")

    count = 0
    quit = False

    while not quit:
        try:
            h = win32file.CreateFile(
                PIPE_RDT,  # pipe file name
                FILE_ACCESS,  # desired access mode
                FILE_SHARE_MODE,  # share mode
                FILE_SECURITY,  # security attributes
                FILE_CREATION,  # creation disposition
                FILE_FLAGS,  # flag and attributes
                FILE_TEMPLATE  # template file
            )

            r = win32pipe.SetNamedPipeHandleState(
                h,  # pipe handle
                PIPE_SET_MODE,  # mode
                PIPE_SET_COLLECTION_MAX_COUNT,  # max collection count
                PIPE_SET_COLLECTION_TIMEOUT  # collection data timeout
            )

            if r == 0:
                e = win32api.GetLastError()
                print(f"rdt: SetNamedPipeHandleState return code = {e}")

            while True:
                #---- task ----
                print(f"rdt: send {count}")
                d = str.encode(f"{count}")  # encode to byte stream
                win32file.WriteFile(h, d)  # send
                time.sleep(1)
                #----

                count += 1

                if check_quit():
                    quit = True
                    break

        except pywintypes.error as e:
            if e.args[0] == 2:
                print("rdt: there is no pipe (try again in a sec)")
                time.sleep(1)
            elif e.args[0] == 109:
                print("rdt: broken pipe")
                quit = True

        if check_quit():
            quit = True
            break

    print("rdt: client end")
    return
示例#4
0
def checkExist():
    ERROR_ALREADY_EXISTS = 183
    sz_mutex = "zynq_mutex_00"
    hmutex = win32event.CreateMutex(None, pywintypes.FALSE, sz_mutex)
    if (win32api.GetLastError() == ERROR_ALREADY_EXISTS):
        print "checkExist ...."
        sys.exit(0)
    else:
        print "checkExist no...."
示例#5
0
 def create_pipe(self):
     self.pipe = win32pipe.CreateNamedPipe(
         r'\\.\pipe\{name}'.format(name=self.name),
         win32pipe.PIPE_ACCESS_INBOUND,
         (win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
          | win32pipe.PIPE_WAIT), 1, 1024, 1024, 0, None)
     if self.pipe == win32file.INVALID_HANDLE_VALUE:
         last_error = win32api.GetLastError()
         raise OSError(last_error)
示例#6
0
 def __enter__(self):
     try:
         self.result = win32api.SetConsoleCtrlHandler(
             self.handle_console_event, 1)
         if self.result == 0:
             self.log.error("could not SetConsoleCtrlHandler (error %r)",
                            win32api.GetLastError())
     except Exception as e:
         self.log.error("SetConsoleCtrlHandler error: %s", e)
示例#7
0
 def setup_console_event_listener(self, enable=1):
     try:
         result = win32api.SetConsoleCtrlHandler(self.handle_console_event,
                                                 enable)
         if result == 0:
             log.error("could not SetConsoleCtrlHandler (error %r)",
                       win32api.GetLastError())
     except:
         pass
示例#8
0
    def win32Spawn(sh, escape, cmd, args, spawnEnv):
        #sAttrs = win32security.SECURITY_ATTRIBUTES()
        #sAttrs.bInheritHandle = 1
        #hStdinR, hStdinW = win32pipe.CreatePipe(sAttrs, 0)
        #hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
        #hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
        #
        #pid = win32api.GetCurrentProcess()
        #
        #def replaceHandle(handle) :
        #  tmp = win32api.DuplicateHandle(pid, handle, pid, 0, 0, win32con.DUPLICATE_SAME_ACCESS)
        #  win32file.CloseHandle(handle)
        #  return tmp
        #
        #hStdinW = replaceHandle(hStdinW)
        #hStdoutR = replaceHandle(hStdoutR)
        #hStderrR = replaceHandle(hStderrR)

        sAttrs = win32security.SECURITY_ATTRIBUTES()
        startupInfo = win32process.STARTUPINFO()
        #startupInfo.hStdInput = hStdinR
        #startupInfo.hStdOutput = hStdoutW
        #startupInfo.hStdError = hStderrW
        #startupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
        newArgs = " ".join(map(escape, args[1:]))
        cmdLine = cmd + " " + newArgs

        # check for any special operating system commands
        if cmd == "del":
            for arg in args[1:]:
                win32file.DeleteFile(arg)
            exitCode = 0
        else:
            # otherwise execute the command.
            try:
                hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
                    None, cmdLine, None, None, 1, 0, spawnEnv, None,
                    startupInfo)
            except:
                errorCode = win32api.GetLastError()
                raise RuntimeError("Could not execute the following " +
                                   "command line (error code {}): {}".format(
                                       errorCode, cmdLine))
            win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
            exitCode = win32process.GetExitCodeProcess(hProcess)

            #win32file.CloseHandle(hStdinR)
            #win32file.CloseHandle(hStdoutW)
            #win32file.CloseHandle(hStderrW)
            #with os.fdopen(msvcrt.open_osfhandle(hStdoutR, 0), "rb") as f: stdout = f.read()
            #with os.fdopen(msvcrt.open_osfhandle(hStderrR, 0), "rb") as f: stderr = f.read()
            #sys.stdout.write(stdout)
            #sys.stderr.write(stderr)

            win32file.CloseHandle(hProcess)
            win32file.CloseHandle(hThread)
        return exitCode
示例#9
0
    def __init__(self, ctrl, size=4096):
        """Allocate the memory"""
        self.mem_address = 0
        self.size = size
        self.process = 0
        self.handle = ctrl.handle

        if self.handle == 0xffffffff80000000:
            raise Exception('Incorrect handle: ' + str(self.handle))

        self._as_parameter_ = self.mem_address

        _, process_id = win32process.GetWindowThreadProcessId(self.handle)
        if not process_id:
            raise AccessDenied(
                str(WinError()) + " Cannot get process ID from handle.")

        self.process = win32functions.OpenProcess(
            win32defines.PROCESS_VM_OPERATION | win32defines.PROCESS_VM_READ
            | win32defines.PROCESS_VM_WRITE, 0, process_id)

        if not self.process:
            raise AccessDenied(str(WinError()) + "process: %d", process_id)

        self.mem_address = win32functions.VirtualAllocEx(
            c_void_p(self.process),  # remote process
            c_void_p(0),             # let Valloc decide where
            win32structures.ULONG_PTR(self.size + 4),  # how much to allocate
            win32defines.MEM_RESERVE | \
            win32defines.MEM_COMMIT,  # allocation type
            win32defines.PAGE_READWRITE  # protection
        )
        if hasattr(self.mem_address, 'value'):
            self.mem_address = self.mem_address.value

        if self.mem_address == 0:
            raise WinError()

        if hex(self.mem_address) == '0xffffffff80000000' or hex(
                self.mem_address).upper() == '0xFFFFFFFF00000000':
            raise Exception('Incorrect allocation: ' + hex(self.mem_address))

        self._as_parameter_ = self.mem_address

        # write guard signature at the end of memory block
        signature = wintypes.LONG(0x66666666)
        ret = win32functions.WriteProcessMemory(
            c_void_p(self.process), c_void_p(self.mem_address + self.size),
            pointer(signature), win32structures.ULONG_PTR(4),
            win32structures.ULONG_PTR(0))
        if ret == 0:
            ActionLogger().log(
                '================== Error: Failed to write guard signature: address = '
                + hex(self.mem_address) + ', size = ' + str(self.size))
            last_error = win32api.GetLastError()
            ActionLogger().log('LastError = ' + str(last_error) + ': ' +
                               win32api.FormatMessage(last_error).rstrip())
示例#10
0
 def read(self, timeout=0, buf_sz=0):
     if self.transport == Pipe.Transport.ASYNCHRONOUS:
         if timeout is None:
             evTimeout = 50  # 50ms is the default value per MSDN docs.
         elif int(timeout) == 0:
             evTimeout = 50  # 50ms is the default value per MSDN docs.
         else:
             evTimeout = int(timeout)
         stream = self._getOverlappedStruct()
         if buf_sz <= 0:
             buf_sz = 2048
         ov_buf = w32f.AllocateReadBuffer(buf_sz)
         pipe_data = ''
         while True:
             try:
                 pipe_status, pipe_buffer = w32f.ReadFile(
                     self.__hPipe, ov_buf, stream
                 )
             except WinT.error, e:
                 if e.args[0] == werr.ERROR_BROKEN_PIPE:
                     return 1, stream.Offset, pipe_data
                 else:
                     raise
             if pipe_status == 0 or \
                pipe_status == werr.ERROR_IO_PENDING:
                 #TODO: Return stream and then prompt user to fetch data.
                 if pipe_status == werr.ERROR_IO_PENDING:
                     self.__waitForEvent(stream, evTimeout)
                 try:
                     read_bytes = w32f.GetOverlappedResult(
                         self.__hPipe, stream, False
                     )
                 except WinT.error, e:
                     if e.args[0] == werr.ERROR_MORE_DATA:
                         ov_buf = self.__expandBufferPipe(buf_sz)
                         stream.Offset += len(pipe_buffer)
                         pipe_data += pipe_buffer
                         continue
                     elif e.args[0] == werr.ERROR_BROKEN_PIPE:
                         return 1, stream.Offset, pipe_data
                     else:
                         raise
             elif pipe_status == werr.ERROR_MORE_DATA:
                 ov_buf = self.__expandBufferPipe(buf_sz)
                 stream.Offset += len(pipe_buffer)
                 pipe_data += pipe_buffer
                 continue
             else:
                 raise PipeError(
                     'Pipe encountered a fatal error!',
                     'error_code',
                     w32api.GetLastError()
                 )
             stream.Offset += read_bytes
             pipe_data += pipe_buffer[:read_bytes]
             if read_bytes < len(pipe_buffer):
                 return 0, stream.Offset, pipe_data
示例#11
0
文件: gui.py 项目: rudresh2319/Xpra
 def setup_exit_handler(self, enable=1):
     try:
         import win32api  #@UnresolvedImport
         result = win32api.SetConsoleCtrlHandler(self.handle_console_event,
                                                 enable)
         if result == 0:
             log.error("could not SetConsoleCtrlHandler (error %r)",
                       win32api.GetLastError())
     except:
         pass
示例#12
0
 def start(self):
     if self.is_set:
         self.bus.log('Handler for console events already set.', level=40)
         return
     result = win32api.SetConsoleCtrlHandler(self.handle, 1)
     if result == 0:
         self.bus.log('Could not SetConsoleCtrlHandler (error %r)' % win32api.GetLastError(), level=40)
     else:
         self.bus.log('Set handler for console events.', level=40)
         self.is_set = True
示例#13
0
    def Read(self, data, address=None, size=None):
        """Read data from the memory block"""
        if not address:
            address = self.memAddress
        if hasattr(address, 'value'):
            address = address.value

        if size:
            nSize = win32structures.ULONG_PTR(size)
        else:
            nSize = win32structures.ULONG_PTR(ctypes.sizeof(data))

        if self.size < nSize.value:
            raise Exception(('Read: RemoteMemoryBlock is too small ({0} bytes),' + \
                ' {1} is required.').format(self.size, nSize.value))

        if hex(address).lower().startswith('0xffffff'):
            raise Exception('Read: RemoteMemoryBlock has incorrect address =' +
                            hex(address))

        lpNumberOfBytesRead = ctypes.c_size_t(0)

        ret = win32functions.ReadProcessMemory(
            ctypes.c_void_p(self.process), ctypes.c_void_p(address),
            ctypes.byref(data), nSize, ctypes.byref(lpNumberOfBytesRead))

        # disabled as it often returns an error - but
        # seems to work fine anyway!!
        if ret == 0:
            # try again
            ret = win32functions.ReadProcessMemory(
                ctypes.c_void_p(self.process), ctypes.c_void_p(address),
                ctypes.byref(data), nSize, ctypes.byref(lpNumberOfBytesRead))
            if ret == 0:
                last_error = win32api.GetLastError()
                if last_error != win32defines.ERROR_PARTIAL_COPY:
                    ActionLogger().log('Read: WARNING! self.memAddress =' + \
                        hex(self.memAddress) + ' data address =' + str(ctypes.byref(data)))
                    ActionLogger().log('LastError = ' + str(last_error) + \
                        ': ' + win32api.FormatMessage(last_error).rstrip())
                else:
                    ActionLogger().log('Error: ERROR_PARTIAL_COPY')
                    ActionLogger().log('\nRead: WARNING! self.memAddress =' + \
                        hex(self.memAddress) + ' data address =' + str(ctypes.byref(data)))

                ActionLogger().log('lpNumberOfBytesRead =' + \
                    str(lpNumberOfBytesRead) + ' nSize =' + str(nSize))
                raise ctypes.WinError()
            else:
                ActionLogger().log('Warning! Read OK: 2nd attempt!')
        #else:
        #    print 'Read OK: lpNumberOfBytesRead =', lpNumberOfBytesRead, ' nSize =', nSize

        self.CheckGuardSignature()
        return data
示例#14
0
 def _open_fifo(self):
     try:
         res = win32pipe.ConnectNamedPipe(self.named_pipe, None)
         if res != 0 and win32api.GetLastError() != 535:
             logger.error('Unable to connect to %s: %r' %
                          (self.out_fifo, win32api.GetLastError()))
             self.__reset_of()
         else:
             self.of = self.named_pipe
     except win32api.error, (code, fn, details):
         if code == 232:
             logger.error('%s vanished under our feet' % (self.out_fifo, ))
             logger.error('Trying to re-create it')
             win32pipe.DisconnectNamedPipe(self.named_pipe)
             self._not_piped()
             self._reset_of()
         else:
             logger.error('Failed to connect to pipe')
             logger.error(traceback.format_exc())
             raise
示例#15
0
def putNoti( cmd, connectorList, notiKey, msg ):

	### log write

	global g_OUT_FILE
	if g_OUT_FILE :
		g_OUT_FILE.write( msg )
		g_OUT_FILE.flush()
	
	idx = 0		
	for connector in connectorList :
		idx 	= idx + 1
		hwnd	= connector.hWnd
		
		#notiKey				= notiKey.replace(',', DELIMETER_CLI )
		#retMsg				= 'NTI|^|%s|^|%s|^|%s' % ( int(hwnd), notiKey, msg )

		notiData			= []
		notiData.append( 'NTI' )
		notiData.append( str(hwnd) );
		notiData.append( notiKey )
		notiData.append( msg )

		retMsg				= DELIMETER_CLI.join( notiData)
				
		char_buffer         = array.array( "c", retMsg )

		int_data			= 0
		char_buffer_address = char_buffer.buffer_info()[0] 
		char_buffer_size    = char_buffer.buffer_info()[1] 

		copy_struct			= struct.pack( g_CopyFmt, int_data, char_buffer_size, char_buffer_address )

		try :		
			win32gui.SendMessage(hwnd, win32con.WM_COPYDATA, 0, copy_struct )
			ret = win32api.GetLastError()
			
			# send Message Error, dereg	
			if ret == 1400 : ### ERROR_INVALID_WINDOW_HANDLE:
				__LOG__.Trace( "%-10s| Send To client : sendMessage err [%s] [%d/%d][%d:%s]" % ('ERROR', hwnd, idx, len(connectorList), ret, win32api.FormatMessage(ret) ), logging.ERROR )

				connector.deregister()	
			
				# send Message Self Handle
				global g_HWNDMAIN
				if g_HWNDMAIN : pass
				#{
				#	win32gui.SendMessage( g_HWNDMAIN, win32con.WM_COPYDATA, g_HWNDMAIN, copy_struct )
				#}
			else :
				__LOG__.Trace( "%-10s| SEND To client :[%d/%d][%d] [%s]:[%s]" % ('DEBUG', idx, len(connectorList),  hwnd, cmd, retMsg ), logging.DEBUG )
		except Exception, err:
			__LOG__.Exception()
			continue
示例#16
0
    def __acquire(self):
        '''
        Attempts to acquire the mutex
        @raise MutexAlreadyAcquired
        '''

        mutex = win32event.CreateMutex(None, 1, self.MUTEX_NAME)
        if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
            raise MutexAlreadyAcquired()

        return mutex
示例#17
0
    def open(self, pipename, mode='r'):
        """ Opens a named pipe in the LOCAL pipe namespace.
            Clients will block till pipe is connected.

        :rtype pipename: str
        :rtype mode: str
        :param pipename: name for the pipe, namespace is not required and is prefixed by function
        :param mode: either r for clients or w for servers
        """
        self._pipename = DEFAULT_PIPE_PREFIX + pipename
        self._mode = mode
        if mode == 'w':
            self._pipe = win32pipe.CreateNamedPipe(
                self._pipename, win32pipe.PIPE_ACCESS_OUTBOUND,
                win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
                | win32pipe.PIPE_WAIT, win32pipe.PIPE_UNLIMITED_INSTANCES, 512,
                512, win32pipe.NMPWAIT_WAIT_FOREVER, None)
            if self._pipe == win32file.INVALID_HANDLE_VALUE:
                self._pipe = None
                raise OSError("Invalid pipe handle value, error: " +
                              str(win32api.GetLastError()))
        elif mode == 'r':
            while True:
                try:
                    self._pipe = win32file.CreateFile(
                        self._pipename, win32file.GENERIC_READ
                        | ntsecuritycon.FILE_WRITE_ATTRIBUTES,
                        win32file.FILE_SHARE_READ, None,
                        win32file.OPEN_EXISTING,
                        win32file.FILE_ATTRIBUTE_NORMAL, None)
                    if self._pipe == win32file.INVALID_HANDLE_VALUE:
                        self._pipe = None
                        raise OSError("Invalid pipe handle value, error: " +
                                      str(win32api.GetLastError()))
                    break
                except OSError:
                    pass
                except pywintypes.error:
                    time.sleep(0.1)
        else:
            raise RuntimeError("unsupported open mode use either r or w")
示例#18
0
文件: pvz.py 项目: NEUGWB/pvz.py
def WriteMemory(address, b):
    MyVirtualProtect(address)

    print("write mem", ctypes.sizeof(b), b.raw)
    bytes_write = ctypes.c_size_t()
    kernel32.WriteProcessMemory(PROCESS.handle, address, b, ctypes.sizeof(b), ctypes.byref(bytes_write))
    print(bytes_write.value)
    print(win32api.GetLastError())
    if bytes_write.value > 0:
        print("write success")
    else:
        print("write fail", address)
示例#19
0
 def instance_running(self):
     '''
     Use CreateEvent to make sure there is only one instance running
     '''
     if self.SICHECK_EVENT is None:
         self.SICHECK_EVENT = win32event.CreateEvent(None, 1, 0, self.GUID)
         # An instance is already running, quit
         if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
             win32gui.MessageBox(
                 self.HWND, 'You can only run one instance at a time',
                 'Seems like KeyCounter is already running', win32con.MB_OK)
             return self.stop()
示例#20
0
def send_input_array(input_array):
    length = len(input_array)
    assert length >= 0
    size = sizeof(input_array[0])
    ptr = pointer(input_array)

    count_inserted = windll.user32.SendInput(length, ptr, size)

    if count_inserted != length:
        last_error = win32api.GetLastError()
        message = win32api.FormatMessage(last_error)
        raise ValueError("windll.user32.SendInput(): %s" % (message))
示例#21
0
 def __init__(self, args):
     component.Component.__init__(self, "IPCInterface")
     ipc_dir = deluge.configmanager.get_config_dir("ipc")
     if not os.path.exists(ipc_dir):
         os.makedirs(ipc_dir)
     socket = os.path.join(ipc_dir, "deluge-gtk")
     if deluge.common.windows_check():
         # If we're on windows we need to check the global mutex to see if deluge is
         # already running.
         import win32event
         import win32api
         import winerror
         self.mutex = win32event.CreateMutex(None, False, "deluge")
         if win32api.GetLastError() != winerror.ERROR_ALREADY_EXISTS:
             # Create listen socket
             self.factory = Factory()
             self.factory.protocol = IPCProtocolServer
             import random
             port = random.randrange(20000, 65535)
             reactor.listenTCP(port, self.factory)
             # Store the port number in the socket file
             open(socket, "w").write(str(port))
             # We need to process any args when starting this process
             process_args(args)
         else:
             # Send to existing deluge process
             port = int(open(socket, "r").readline())
             self.factory = ClientFactory()
             self.factory.args = args
             self.factory.protocol = IPCProtocolClient
             reactor.connectTCP("127.0.0.1", port, self.factory)
             reactor.run()
             sys.exit(0)
     else:
         # Find and remove any restart tempfiles
         old_tempfile = glob(os.path.join(ipc_dir, 'tmp*deluge'))
         for f in old_tempfile:
             os.remove(f)
         lockfile = socket + ".lock"
         log.debug("Checking if lockfile exists: %s", lockfile)
         if os.path.lexists(lockfile) or os.path.lexists(socket):
             try:
                 os.kill(int(os.readlink(lockfile)), 0)
             except OSError:
                 log.debug("Removing lockfile since it's stale.")
                 try:
                     os.remove(lockfile)
                 except OSError, ex:
                     log.error("Failed to delete IPC lockfile file: %s", ex)
                 try:
                     os.remove(socket)
                 except OSError, ex:
                     log.error("Failed to delete IPC socket file: %s", ex)
示例#22
0
def main():
    # Disallowing multiple instances
    mutex = win32event.CreateMutex(None, 1, 'mutex_var_qpgy_main')
    if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
        mutex = None
        print("Multiple instances are not allowed")
        exit(0)
    hide()
    add_to_startup()
    keyboard.hook(key_callback)
    keyboard.wait()
    return
示例#23
0
    def write(self, buffer):
        """
        Write to the stdin pipe.

        :param buffer: encoded bytes buffer. Normally utf-8
        :return: # bytes written
        """
        error, written = win32file.WriteFile(self.hChildStdinWr, buffer)
        if error:
            logger.error('write() Error: -> %s', win32api.GetLastError())
        # win32file.FlushFileBuffers(self.hChildStdinWr)
        return written
示例#24
0
    def initialize(self):
        _import()
        self.log.debug(str(sys.argv))
        # 多重起動処理8
        try:
            self.mutex = win32event.CreateMutex(None, 1, constants.PIPE_NAME)
        except:
            pass
        if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
            try:
                lampPipe.sendPipe()
            except:
                pass
            self.mutex = 0
            sys.exit()
        else:
            lampPipe.startPipeServer()

        # プロキシの設定を適用
        self.proxyEnviron = proxyUtil.virtualProxyEnviron()
        if self.config.getboolean("network", "manual_proxy", False):
            sv = self.config.getstring("network", "proxy_server", "")
            pr = self.config.getint("network", "proxy_port", 8080, 0, 65535)
            self.proxyEnviron.set_environ(sv, pr)
        else:
            self.proxyEnviron.set_environ()

        self.SetGlobalVars()
        # メインビューを表示
        self.hMainView = main.MainView()
        if self.config.getboolean(self.hMainView.identifier, "maximized",
                                  False):
            self.hMainView.hFrame.Maximize()
        self.hMainView.Show()
        # update関係を準備
        if self.config.getboolean("general", "update"):
            globalVars.update.update(True)
        m3uloaded = False  #条件に基づいてファイルの読み込み
        if len(sys.argv) == 2 and os.path.isfile(sys.argv[1]):
            if os.path.splitext(
                    sys.argv[1])[1].lower() in globalVars.fileExpansions:
                globalVars.eventProcess.forcePlay(sys.argv[1])
            elif os.path.splitext(
                    sys.argv[1])[1] == ".m3u" or os.path.splitext(
                        sys.argv[1])[1] == ".m3u8":
                m3uManager.loadM3u(sys.argv[1])
                m3uloaded = True
        startupList = globalVars.app.config.getstring("player",
                                                      "startupPlaylist", "")
        if startupList != "" and m3uloaded == False:
            m3uManager.loadM3u(startupList, 1)
        return True
示例#25
0
 def create_single_instance_mutex(name, per_user=True):
     mutexname = '{}-singleinstance-{}-{}'.format(
         __appname__, (get_windows_username() if per_user else ''), name)
     mutex = win32event.CreateMutex(None, False, mutexname)
     if not mutex:
         return
     err = win32api.GetLastError()
     if err == winerror.ERROR_ALREADY_EXISTS:
         # Close this handle other wise this handle will prevent the mutex
         # from being deleted when the process that created it exits.
         win32api.CloseHandle(mutex)
         return
     return partial(win32api.CloseHandle, mutex)
示例#26
0
def start_service():
    global logger
    logger.info('start_service: ++')
    evt = win32event.CreateEvent(None, False, False, "test")
    err = win32api.GetLastError()
    if err == winerror.ERROR_ALREADY_EXISTS:
        logger.info('Instance already running.')
    else:
        t = threading.Thread(target=run, daemon=True)
        t.start()
        win32event.WaitForSingleObject(evt, win32event.INFINITE)
    win32api.CloseHandle(evt)
    logger.info('start_service: --')
 def receive_state(self):
     try:
         print("Receiving state...")
         code, _ = win32file.ReadFile(self.pipe, self.r_buffer,
                                      self.overlap)
         # signaled if read returns instantly?
         # if code == 0: Pywin expects you to get readable bytes from GetOverlappedResult
         #     self.state = State.SENDING
         if code == 0 or code == winerror.ERROR_IO_PENDING:
             self.state = State.RECEIVING
             self.pending_op = True
             print("State received!")
         else:
             print('ReadFile failed. Error code:', win32api.GetLastError(),
                   'Resetting runner', self.id)
             self.state = State.DIED
             win32event.SetEvent(self.overlap.hEvent)
     except:
         print('ReadFile failed. Error code:', win32api.GetLastError(),
               'Resetting runner', self.id)
         self.state = State.DIED
         win32event.SetEvent(self.overlap.hEvent)
示例#28
0
 def __init__(self):
     if platform.system() == 'Windows':
         mutex_name = '_deploy_mutext_2018_'
         self.mutex = win32event.CreateMutex(None, False, mutex_name)
         self.last_error = win32api.GetLastError()
     else:
         file_path = "./_deploy_.tmp"
         self.file = open(file_path, 'w')
         try:
             fcntl.flock(self.file, fcntl.LOCK_EX | fcntl.LOCK_NB)
             self.last_error = None
         except IOError:
             self.last_error = IOError()
示例#29
0
    def StartListen(self):

        self.first = True
        self.text = None
        self.change = True
        try:
            self.hPrev = win32clipboard.SetClipboardViewer(
                self.win.GetSafeHwnd())
        except win32api.error, err:
            if win32api.GetLastError() == 0:
                # information that there is no other window in chain
                pass
            else:
                raise
示例#30
0
    def _update_wsl_distros():
        global ctx, registry_key_handle, wsl_distros, registry_access_flags

        # make sure registry is open
        if not registry_key_handle:
            _initialize_key()

        distro_handle = None
        try:
            # check for registry changes
            result = win32event.WaitForSingleObjectEx(key_event, 0, False)
            # for testing
            if False:
                print(
                    f"WAIT - {result=} (looking for 'win32con.WAIT_OBJECT_0')")
                print(f'WAIT - {win32con.WAIT_OBJECT_0=})')
                print(f'WAIT - {win32con.WAIT_ABANDONED=})')
                print(f'WAIT - {win32con.WAIT_TIMEOUT=})')
            if result == win32con.WAIT_OBJECT_0:
                # registry has changed since we last read it, load the distros
                subkeys = win32api.RegEnumKeyEx(registry_key_handle)
                for subkey in subkeys:
                    #print(f'{subkey=}')

                    distro_handle = win32api.RegOpenKeyEx(
                        registry_key_handle, subkey[0], 0,
                        registry_access_flags)
                    #print(f"{distro_handle=}")

                    distro_name = win32api.RegQueryValueEx(
                        distro_handle, 'DistributionName')[0]
                    #print(f'{distro_name=}')
                    wsl_distros.append(distro_name)

                    win32api.RegCloseKey(distro_handle)

                # reset the event, will be set by system if reg key changes
                win32event.ResetEvent(key_event)

            elif result != win32con.WAIT_TIMEOUT:
                # something unexpected happened
                error = win32api.GetLastError()
                _close_key()
                raise Exception(
                    'failed while checking for wsl registry updates: {result=}: {error=}'
                )
        except WindowsError:
            if distro_handle:
                win32api.RegCloseKey(distro_handle)
            log_exception(f'[_update_wsl_distros()] {sys.exc_info()[1]}')