Python win32file.error() Examples

The following are 18 code examples of win32file.error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32file , or try the search function .
Example #1
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 8 votes vote down vote up
def testSimpleFiles(self):
        try:
            fd, filename = tempfile.mkstemp()
        except AttributeError:
            self.fail("This test requires Python 2.3 or later")
        os.close(fd)
        os.unlink(filename)
        handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None)
        test_data = str2bytes("Hello\0there")
        try:
            win32file.WriteFile(handle, test_data)
            handle.Close()
            # Try and open for read
            handle = win32file.CreateFile(filename, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
            rc, data = win32file.ReadFile(handle, 1024)
            self.assertEquals(data, test_data)
        finally:
            handle.Close()
            try:
                os.unlink(filename)
            except os.error:
                pass

    # A simple test using normal read/write operations. 
Example #2
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testCompletionPortsMultiple(self):
        # Mainly checking that we can "associate" an existing handle.  This
        # failed in build 203.
        ioport = win32file.CreateIoCompletionPort(win32file.INVALID_HANDLE_VALUE,
                                                  0, 0, 0)
        socks = []
        for PORT in range(9123, 9125):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(('', PORT))
            sock.listen(1)
            socks.append(sock)
            new = win32file.CreateIoCompletionPort(sock.fileno(), ioport, PORT, 0)
            assert new is ioport
        for s in socks:
            s.close()
        hv = int(ioport)
        ioport = new = None
        # The handle itself should be closed now (unless we leak references!)
        # Check that.
        try:
            win32file.CloseHandle(hv)
            raise RuntimeError("Expected close to fail!")
        except win32file.error, details:
            self.failUnlessEqual(details.winerror, winerror.ERROR_INVALID_HANDLE) 
Example #3
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _IOCPServerThread(self, handle, port, drop_overlapped_reference):
        overlapped = pywintypes.OVERLAPPED()
        win32pipe.ConnectNamedPipe(handle, overlapped)
        if drop_overlapped_reference:
            # Be naughty - the overlapped object is now dead, but
            # GetQueuedCompletionStatus will still find it.  Our check of
            # reference counting should catch that error.
            overlapped = None
            # even if we fail, be sure to close the handle; prevents hangs
            # on Vista 64...
            try:
                self.failUnlessRaises(RuntimeError,
                                      win32file.GetQueuedCompletionStatus, port, -1)
            finally:
                handle.Close()
            return

        result = win32file.GetQueuedCompletionStatus(port, -1)
        ol2 = result[-1]
        self.failUnless(ol2 is overlapped)
        data = win32file.ReadFile(handle, 512)[1]
        win32file.WriteFile(handle, data) 
Example #4
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testEmptyDir(self):
        test_path = os.path.join(win32api.GetTempPath(), "win32file_test_directory")
        try:
            # Note: previously used shutil.rmtree, but when looking for
            # reference count leaks, that function showed leaks!  os.rmdir
            # doesn't have that problem.
            os.rmdir(test_path)
        except os.error:
            pass
        os.mkdir(test_path)
        try:
            num = 0
            for i in win32file.FindFilesIterator(os.path.join(test_path, "*")):
                num += 1
            # Expecting "." and ".." only
            self.failUnlessEqual(2, num)
        finally:
            os.rmdir(test_path) 
Example #5
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_connect_with_payload(self):
        giveup_event = win32event.CreateEvent(None, 0, 0, None)
        t = threading.Thread(target=self.connect_thread_runner,
                             args=(True, giveup_event))
        t.start()
        time.sleep(0.1)
        s2 = socket.socket()
        ol = pywintypes.OVERLAPPED()
        s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand
        try:
            win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request"))
        except win32file.error, exc:
            win32event.SetEvent(giveup_event)
            if exc.winerror == 10022: # WSAEINVAL
                raise TestSkipped("ConnectEx is not available on this platform")
            raise # some error error we don't expect. 
Example #6
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_connect_without_payload(self):
        giveup_event = win32event.CreateEvent(None, 0, 0, None)
        t = threading.Thread(target=self.connect_thread_runner,
                             args=(False, giveup_event))
        t.start()
        time.sleep(0.1)
        s2 = socket.socket()
        ol = pywintypes.OVERLAPPED()
        s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand
        try:
            win32file.ConnectEx(s2, self.addr, ol)
        except win32file.error, exc:
            win32event.SetEvent(giveup_event)
            if exc.winerror == 10022: # WSAEINVAL
                raise TestSkipped("ConnectEx is not available on this platform")
            raise # some error error we don't expect. 
Example #7
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def lseek(self, port, pos, how):
        """
        Use lseek on the device. The device is unseekable so PASS is returned
        when lseek command fails and vice versa.

        :param port: Name of the port
        :param pos: Offset
        :param how: Relative offset os.SEEK_{SET,CUR,END}
        """
        fd = self._open([port])[0]

        try:
            os.lseek(fd, pos, how)
        except Exception as inst:
            if inst.errno == 29:
                print("PASS: the lseek failed as expected")
            else:
                print(inst)
                print("FAIL: unknown error")
        else:
            print("FAIL: the lseek unexpectedly passed") 
Example #8
Source File: mpv.py    From trakt-scrobbler with GNU General Public License v2.0 6 votes vote down vote up
def handle_cmd_response(self, resp):
        command = self.sent_commands[resp['request_id']]['command']
        del self.sent_commands[resp['request_id']]
        if resp['error'] != 'success':
            logger.error(f'Error with command {command!s}. Response: {resp!s}')
            return
        elif command[0] != 'get_property':
            return
        param = command[1]
        data = resp['data']
        if param == 'pause':
            self.vars['state'] = 1 if data else 2
        if param in self.WATCHED_PROPS:
            self.vars[param] = data
            self.updated_props_count += 1
        if self.updated_props_count == len(self.WATCHED_PROPS):
            self.update_status() 
Example #9
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def close(self, filepath):
        """
        Close open port.

        :param filepath: File to close.
        """
        hFile = None
        path = self.ports[filepath]["path"]
        if path is not None:
            if path in list(self.files.keys()):
                hFile = self.files[path]
                del self.files[path]
            if hFile is not None:
                try:
                    win32file.CloseHandle(hFile)
                except win32file.error as inst:
                    print("FAIL: Closing the file: " + str(inst))
                    return
        print("PASS: Close") 
Example #10
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def open(self, name):
        """
        Direct open devices.

        :param name: Port name.
        :return: 0 on success
        """
        path = self.ports[name]['path']
        try:
            self.files[path] = win32file.CreateFile(path,
                                                    win32file.GENERIC_WRITE |
                                                    win32file.GENERIC_READ,
                                                    0,
                                                    None,
                                                    win32file.OPEN_EXISTING,
                                                    win32file.FILE_ATTRIBUTE_NORMAL,
                                                    None)
        except win32file.error as exc_detail:
            print("%s\nFAIL: Failed open file %s" % (str(exc_detail), name))
            return exc_detail
        print("PASS: All files opened correctly.") 
Example #11
Source File: nt.py    From deplicate with MIT License 6 votes vote down vote up
def blksize(path):
    """
    Get optimal file system buffer size (in bytes) for I/O calls.
    """
    diskfreespace = win32file.GetDiskFreeSpace
    dirname = os.path.dirname(fullpath(path))
    try:
        cluster_sectors, sector_size = diskfreespace(dirname)[:2]
        size = cluster_sectors * sector_size

    except win32file.error as e:
        if e.winerror != winerror.ERROR_NOT_READY:
            raise
        sleep(3)
        size = blksize(dirname)

    return size 
Example #12
Source File: filechooser.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def is_hidden(self, fn):
        if platform == 'win':
            if not _have_win32file:
                return False
            try:
                return GetFileAttributesExW(fn)[0] & FILE_ATTRIBUTE_HIDDEN
            except error:
                # This error can occured when a file is already accessed by
                # someone else. So don't return to True, because we have lot
                # of chances to not being able to do anything with it.
                Logger.exception('unable to access to <%s>' % fn)
                return True

        return basename(fn).startswith('.') 
Example #13
Source File: filechooser.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def is_hidden(self, fn):
        if platform == 'win':
            if not _have_win32file:
                return False
            try:
                return GetFileAttributesExW(fn)[0] & FILE_ATTRIBUTE_HIDDEN
            except error:
                # This error can occured when a file is already accessed by
                # someone else. So don't return to True, because we have lot
                # of chances to not being able to do anything with it.
                Logger.exception('unable to access to <%s>' % fn)
                return True

        return basename(fn).startswith('.') 
Example #14
Source File: mpv.py    From trakt-scrobbler with GNU General Public License v2.0 5 votes vote down vote up
def conn_loop(self):
        self.is_running = True
        self.update_vars()
        self.file_handle = win32file.CreateFile(
            self.ipc_path,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0, None,
            win32file.OPEN_EXISTING,
            0, None
        )
        while self.is_running:
            try:
                while not self.write_queue.empty():
                    win32file.WriteFile(
                        self.file_handle, self.write_queue.get_nowait())
            except win32file.error:
                logger.debug('Exception while writing to pipe.', exc_info=True)
                self.is_running = False
                break
            size = win32file.GetFileSize(self.file_handle)
            if size > 0:
                while size > 0:
                    # pipe has data to read
                    _, data = win32file.ReadFile(self.file_handle, 4096)
                    self.on_data(data)
                    size = win32file.GetFileSize(self.file_handle)
            else:
                time.sleep(1)
        win32file.CloseHandle(self.file_handle)
        logger.debug('Pipe closed.') 
Example #15
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testEncrypt(self):
        fname = tempfile.mktemp("win32file_test")
        f = open(fname, "wb")
        f.write(str2bytes("hello"))
        f.close()
        f = None
        try:
            try:
                win32file.EncryptFile(fname)
            except win32file.error, details:
                if details.winerror != winerror.ERROR_ACCESS_DENIED:
                    raise
                print "It appears this is not NTFS - cant encrypt/decrypt"
            win32file.DecryptFile(fname) 
Example #16
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testCompletionPortsNonQueued(self, test_overlapped_death = 0):
        # In 204 we had a reference count bug when OVERLAPPED objects were
        # associated with a completion port other than via
        # PostQueuedCompletionStatus.  This test is based on the reproduction
        # reported with that bug.
        # Create the pipe.
        BUFSIZE = 512
        pipe_name = r"\\.\pipe\pywin32_test_pipe"
        handle = win32pipe.CreateNamedPipe(pipe_name,
                          win32pipe.PIPE_ACCESS_DUPLEX|
                          win32file.FILE_FLAG_OVERLAPPED,
                          win32pipe.PIPE_TYPE_MESSAGE|
                          win32pipe.PIPE_READMODE_MESSAGE|
                          win32pipe.PIPE_WAIT,
                          1, BUFSIZE, BUFSIZE,
                          win32pipe.NMPWAIT_WAIT_FOREVER,
                          None)
        # Create an IOCP and associate it with the handle.        
        port = win32file.CreateIoCompletionPort(-1, 0, 0, 0)
        win32file.CreateIoCompletionPort(handle, port, 1, 0)

        t = threading.Thread(target=self._IOCPServerThread, args=(handle,port, test_overlapped_death))
        t.setDaemon(True) # avoid hanging entire test suite on failure.
        t.start()
        try:
            time.sleep(0.1) # let thread do its thing.
            try:
                win32pipe.CallNamedPipe(r"\\.\pipe\pywin32_test_pipe", str2bytes("Hello there"), BUFSIZE, 0)
            except win32pipe.error:
                # Testing for overlapped death causes this
                if not test_overlapped_death:
                    raise
        finally:
            if not test_overlapped_death:
                handle.Close()
            t.join(3)
            self.failIf(t.isAlive(), "thread didn't finish") 
Example #17
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testSimpleOverlapped(self):
        # Create a file in the %TEMP% directory.
        import win32event
        testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
        desiredAccess = win32file.GENERIC_WRITE
        overlapped = pywintypes.OVERLAPPED()
        evt = win32event.CreateEvent(None, 0, 0, None)
        overlapped.hEvent = evt
        # Create the file and write shit-loads of data to it.
        h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0)
        chunk_data = str2bytes("z") * 0x8000
        num_loops = 512
        expected_size = num_loops * len(chunk_data)
        for i in range(num_loops):
            win32file.WriteFile(h, chunk_data, overlapped)
            win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
            overlapped.Offset = overlapped.Offset + len(chunk_data)
        h.Close()
        # Now read the data back overlapped
        overlapped = pywintypes.OVERLAPPED()
        evt = win32event.CreateEvent(None, 0, 0, None)
        overlapped.hEvent = evt
        desiredAccess = win32file.GENERIC_READ
        h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.OPEN_EXISTING, 0, 0)
        buffer = win32file.AllocateReadBuffer(0xFFFF)
        while 1:
            try:
                hr, data = win32file.ReadFile(h, buffer, overlapped)
                win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
                overlapped.Offset = overlapped.Offset + len(data)
                if not data is buffer:
                    self.fail("Unexpected result from ReadFile - should be the same buffer we passed it")
            except win32api.error:
                break
        h.Close() 
Example #18
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 4 votes vote down vote up
def init(self, in_files):
        """
        Init and check port properties.
        """
        # This only sets the ports names and paths
        # TODO: symlinks are sometimes missing, use /dev/vport%dp%d"
        self.ports = self._get_port_status(in_files)

        # Check if all ports really exists
        remove = []
        for item in six.iteritems(self.ports):
            port = item[1]
            try:
                hFile = win32file.CreateFile(port['path'], 0, 0, None,
                                             win32file.OPEN_EXISTING,
                                             win32file.FILE_ATTRIBUTE_NORMAL,
                                             None)
                win32file.CloseHandle(hFile)
            except win32file.error:
                remove.append(port['name'])
                print("Fail to open port %s" % port['name'])
        for name in remove:
            del(self.ports[name])

        # Check if in_files count and system port count matches
        # TODO: Not all devices are listed
        # TODO: Find the way to list all devices
        if remove:
            print("FAIL: Not all ports are present, check the log.")
            return
        """
        reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "System")
        reg = _winreg.OpenKey(reg, "CurrentControlSet")
        reg = _winreg.OpenKey(reg, "Services")
        reg = _winreg.OpenKey(reg, "VirtioSerial")
        reg = _winreg.OpenKey(reg, "Enum")
        virtio_port_count = _winreg.QueryValueEx(reg, "Count")[0]
        if virtio_port_count != len(self.ports):
            print("FAIL: Number of ports (%d) doesn't match the number"
                  " of ports in registry (%d)"
                  % (len(self.ports), virtio_port_count))
            return
        """

        print("PASS: Init and check virtioconsole files in system.")