Python win32file.WriteFile() Examples

The following are 30 code examples of win32file.WriteFile(). 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: win32.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def ZapMBRGPT(self, disk_size, sector_size, add1MB):
        self.assert_physical_drive()
        # Implementation borrowed from rufus: https://github.com/pbatard/rufus
        num_sectors_to_clear \
            = (add1MB and 2048 or 0) + self.MAX_SECTORS_TO_CLEAR
        zeroBuf = b'\0' * sector_size
        for i in range(num_sectors_to_clear):
            self.WriteFile(zeroBuf)
        offset = disk_size - self.MAX_SECTORS_TO_CLEAR * sector_size
        win32file.SetFilePointer(self.h, offset, win32con.FILE_BEGIN)
        for i in range(num_sectors_to_clear):
            self.WriteFile(zeroBuf)
        # We need to append paddings as CREATE_DISK structure contains a union.
        param = struct.pack('<IIIHH8s',
                            winioctlcon.PARTITION_STYLE_MBR, 0xdeadbeef,
                            0,0,0,b'abcdefgh')
        win32file.DeviceIoControl(
            self.h, winioctlcon.IOCTL_DISK_CREATE_DISK, param, 0, None) 
Example #3
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def _none_mode(self):
            """
            Read and write to device in blocking mode
            """
            data = ""
            while not self.exit_thread.isSet():
                data = ""
                for desc in self.in_files:
                    ret, _data = win32file.ReadFile(desc, self.cachesize)
                    if ret:
                        msg = ("Error occurred while receiving data, "
                               "err=%s, read=%s" % (ret, _data))
                        print("FAIL: " + msg)
                        raise IOError(msg)
                    data += _data
                if data != "":
                    for desc in self.out_files:
                        ret, _data = win32file.WriteFile(desc, data)
                        if ret:
                            msg = ("Error occurred while sending data, "
                                   "err=%s, sentlen=%s" % (ret, _data))
                            print("FAIL: " + msg)
                            raise IOError(msg) 
Example #4
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def Stop(self):
        """
        This will be called to stop the thread.
        """
        if self.file:
            writeOvlap = win32file.OVERLAPPED()
            writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
            msg = "q".encode("ascii")
            win32file.WriteFile(self.file, msg, writeOvlap)
            win32file.CloseHandle(self.file)
            self.file = None
        self.keepRunning = False

        if self.service:
            win32service.CloseServiceHandle(self.service)

        #eg.PrintNotice("MCE_Vista: stopping thread") 
Example #5
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 #6
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def Transmit(self, transmitData):
        """
        This will be called to detect available IR Blasters.
        """
        if not self.file:
            if not self.connecting:
                self.Connect()
            else:
                return False
        while self.receiving:
            time.sleep(0.05)
        writeOvlap = win32file.OVERLAPPED()
        writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
        win32file.WriteFile(self.file, transmitData, writeOvlap)
        win32event.WaitForSingleObject(writeOvlap.hEvent, win32event.INFINITE)
        return True 
Example #7
Source File: TestCmd.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send(self, input):
            input = to_bytes(input)
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception) as why:
                if why.args[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise

            return written 
Example #8
Source File: win32fileDemo.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def SimpleFileDemo():
    testName = os.path.join( win32api.GetTempPath(), "win32file_demo_test_file")
    if os.path.exists(testName): os.unlink(testName)
    # Open the file for writing.
    handle = win32file.CreateFile(testName, 
                                  win32file.GENERIC_WRITE, 
                                  0, 
                                  None, 
                                  win32con.CREATE_NEW, 
                                  0, 
                                  None)
    test_data = "Hello\0there".encode("ascii")
    win32file.WriteFile(handle, test_data)
    handle.Close()
    # Open it for reading.
    handle = win32file.CreateFile(testName, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
    rc, data = win32file.ReadFile(handle, 1024)
    handle.Close()
    if data == test_data:
        print "Successfully wrote and read a file"
    else:
        raise Exception("Got different data back???")
    os.unlink(testName) 
Example #9
Source File: _pollingfile.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def checkWork(self):
        numBytesWritten = 0
        if not self.outQueue:
            if self.disconnecting:
                self.writeConnectionLost()
                return 0
            try:
                win32file.WriteFile(self.writePipe, '', None)
            except pywintypes.error:
                self.writeConnectionLost()
                return numBytesWritten
        while self.outQueue:
            data = self.outQueue.pop(0)
            errCode = 0
            try:
                errCode, nBytesWritten = win32file.WriteFile(self.writePipe,
                                                             data, None)
            except win32api.error:
                self.writeConnectionLost()
                break
            else:
                # assert not errCode, "wtf an error code???"
                numBytesWritten += nBytesWritten
                if len(data) > nBytesWritten:
                    self.outQueue.insert(0, data[nBytesWritten:])
                    break
        else:
            resumed = self.bufferEmpty()
            if not resumed and self.disconnecting:
                self.writeConnectionLost()
        return numBytesWritten 
Example #10
Source File: subprocessng.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception), why:
                if why[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise 
Example #11
Source File: TestCmd.py    From android-xmrig-miner with GNU General Public License v3.0 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception), why:
                if why[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise 
Example #12
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception):
                if geterror()[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise

            return written 
Example #13
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def WriteFile(handle, data, ol = None):
            c_written = DWORD()
            success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol)
            return ctypes.windll.kernel32.GetLastError(), c_written.value 
Example #14
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception):
                if geterror()[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise

            return written 
Example #15
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def WriteFile(handle, data, ol = None):
            c_written = DWORD()
            success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol)
            return ctypes.windll.kernel32.GetLastError(), c_written.value 
Example #16
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def WriteFile(handle, data, ol = None):
            c_written = DWORD()
            success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol)
            return ctypes.windll.kernel32.GetLastError(), c_written.value 
Example #17
Source File: win32.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def WriteFile(self, b):
        return win32file.WriteFile(self.h, b, None) 
Example #18
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def WriteFile(handle, data, ol = None):
            c_written = DWORD()
            success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol)
            return ctypes.windll.kernel32.GetLastError(), c_written.value 
Example #19
Source File: _win32serialport.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def write(self, data):
        if data:
            if self.writeInProgress:
                self.outQueue.append(data)
            else:
                self.writeInProgress = 1
                win32file.WriteFile(self._serial.hComPort, data, self._overlappedWrite) 
Example #20
Source File: _win32serialport.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def write(self, data):
        if data:
            if self.writeInProgress:
                self.outQueue.append(data)
            else:
                self.writeInProgress = 1
                win32file.WriteFile(self._serial.hComPort, data, self._overlappedWrite) 
Example #21
Source File: pcapd.py    From pymobiledevice with GNU General Public License v3.0 5 votes vote down vote up
def writePacket(self, packet):
        t = time.time()
        pkthdr = struct.pack("<LLLL", int(t), int(t*1000000 % 1000000), len(packet), len(packet))
        errCode, nBytesWritten = win32file.WriteFile(self.pipe, pkthdr + packet)
        return errCode == 0 
Example #22
Source File: pcapd.py    From pymobiledevice with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pipename=r'\\.\pipe\wireshark'):
        self.pipe = win32pipe.CreateNamedPipe(pipename,
                                           win32pipe.PIPE_ACCESS_OUTBOUND,
                                           win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
                                           1, 65536, 65536,
                                           300,
                                           None)
        print("Connect wireshark to %s" % pipename)
        win32pipe.ConnectNamedPipe(self.pipe, None)
        win32file.WriteFile(self.pipe, struct.pack("<LHHLLLL", 0xa1b2c3d4, 2, 4, 0, 0, 65535, LINKTYPE_ETHERNET)) 
Example #23
Source File: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def write(self, content):
            """Writes the bytes to the connected client.

            @param content: The bytes
            @type content: str
            """
            win32file.WriteFile(self.__pipe_handle, content) 
Example #24
Source File: async_sub.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception):
                if geterror()[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise

            return written 
Example #25
Source File: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def close(self):
            """Closes the channel to the client.
            """
            try:
                # 2->TODO struct.pack|unpack in python < 2.7.7 does not allow unicode format string.
                win32file.WriteFile(
                    self.__pipe_handle, compat.struct_pack_unicode("I", 0)
                )
                win32file.FlushFileBuffers(self.__pipe_handle)
            finally:
                win32pipe.DisconnectNamedPipe(self.__pipe_handle)
                self.__pipe_handle = None 
Example #26
Source File: TestCmd.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception) as why:
                if why[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise

            return written 
Example #27
Source File: TestCmd.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception) as why:
                if why[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise

            return written 
Example #28
Source File: TestCmd.py    From kawalpemilu2014 with GNU Affero General Public License v3.0 5 votes vote down vote up
def send(self, input):
            if not self.stdin:
                return None

            try:
                x = msvcrt.get_osfhandle(self.stdin.fileno())
                (errCode, written) = WriteFile(x, input)
            except ValueError:
                return self._close('stdin')
            except (subprocess.pywintypes.error, Exception), why:
                if why[0] in (109, errno.ESHUTDOWN):
                    return self._close('stdin')
                raise 
Example #29
Source File: _win32serialport.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def serialWriteEvent(self):
        try:
            dataToWrite = self.outQueue.pop(0)
        except IndexError:
            self.writeInProgress = 0
            return
        else:
            win32file.WriteFile(self._serial.hComPort, dataToWrite, self._overlappedWrite) 
Example #30
Source File: _pollingfile.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def checkWork(self):
        numBytesWritten = 0
        if not self.outQueue:
            if self.disconnecting:
                self.writeConnectionLost()
                return 0
            try:
                win32file.WriteFile(self.writePipe, '', None)
            except pywintypes.error:
                self.writeConnectionLost()
                return numBytesWritten
        while self.outQueue:
            data = self.outQueue.pop(0)
            errCode = 0
            if isinstance(data, unicode):
                raise TypeError("unicode not allowed")
            try:
                errCode, nBytesWritten = win32file.WriteFile(self.writePipe,
                                                             data, None)
            except win32api.error:
                self.writeConnectionLost()
                break
            else:
                # assert not errCode, "wtf an error code???"
                numBytesWritten += nBytesWritten
                if len(data) > nBytesWritten:
                    self.outQueue.insert(0, data[nBytesWritten:])
                    break
        else:
            resumed = self.bufferEmpty()
            if not resumed and self.disconnecting:
                self.writeConnectionLost()
        return numBytesWritten