Python win32file.CreateFile() Examples

The following are 30 code examples of win32file.CreateFile(). 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: windows_support.py    From avocado-vt with GNU General Public License v2.0 7 votes vote down vote up
def __init__(self, filename):
        self._hfile = win32file.CreateFile(filename,
                                           win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                                           win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
                                           win32security.SECURITY_ATTRIBUTES(),
                                           win32con.OPEN_EXISTING,
                                           win32con.FILE_FLAG_OVERLAPPED,
                                           0)
        self._read_ovrlpd = pywintypes.OVERLAPPED()
        self._read_ovrlpd.hEvent = win32event.CreateEvent(None, True,
                                                          False, None)
        self._write_ovrlpd = pywintypes.OVERLAPPED()
        self._write_ovrlpd.hEvent = win32event.CreateEvent(None, True,
                                                           False, None)
        self._bufs = []
        self._n = 0 
Example #3
Source File: win32.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def _openHandle(path, bWriteAccess, bWriteShare,
                logfunc = lambda s: None):
    TIMEOUT, NUM_RETRIES = 10, 20
    for retry_count in range(6):
        try:
            access_flag = win32con.GENERIC_READ | \
                          (bWriteAccess and win32con.GENERIC_WRITE or 0)
            share_flag = win32con.FILE_SHARE_READ | \
                         (bWriteShare and win32con.FILE_SHARE_WRITE or 0)
            handle = win32file.CreateFile(
                path, access_flag, share_flag, None,
                win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
            nth = { 0: 'first', 1:'second', 2:'third'}
            logfunc("Opening [%s]: success at the %s iteration" %
                    (path, nth.get(retry_count, '%sth' % (retry_count+1))))
            return handle
        except pywintypes.error as e:
            logfunc('Exception=>'+str(e))
            if NUM_RETRIES/3 < retry_count:
                bWriteShare = True
        time.sleep(TIMEOUT / float(NUM_RETRIES))
    else:
        raise RuntimeError("Couldn't open handle for %s." % path) 
Example #4
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 #5
Source File: WindowsServer.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def CreateFile(self, fname, mode="r", bufsize=-1):
        "Open a file the same way a File Directory migration engine would."
        fname = cygwin2nt(fname)
        UserLog.msg("CreateFile", fname)
        if mode == "r":
            wmode = win32file.GENERIC_READ
        elif mode == "w":
            wmode = win32file.GENERIC_WRITE
        elif mode in ( 'r+', 'w+', 'a+'):
            wmode = win32file.GENERIC_READ | win32file.GENERIC_WRITE
        else:
            raise ValueError, "invalid file mode"
        h = win32file.CreateFile(
            fname,                           #  CTSTR lpFileName,
            wmode,                           #  DWORD dwDesiredAccess,
            win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, #  DWORD dwShareMode,
            None,                            #  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
            win32file.OPEN_EXISTING,         #  DWORD dwCreationDisposition,
            win32file.FILE_ATTRIBUTE_NORMAL, #  DWORD dwFlagsAndAttributes,
            0,                               #  HANDLE hTemplateFile
            )
        self._files[int(h)] = h
        return int(h) 
Example #6
Source File: pysynch.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def CopyFileToCe(src_name, dest_name, progress = None):
    sh = win32file.CreateFile(src_name, win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
    bytes=0
    try:
        dh = wincerapi.CeCreateFile(dest_name, win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
        try:
            while 1:
                hr, data = win32file.ReadFile(sh, 2048)
                if not data:
                    break
                wincerapi.CeWriteFile(dh, data)
                bytes = bytes + len(data)
                if progress is not None: progress(bytes)
        finally:
            pass
            dh.Close()
    finally:
        sh.Close()
    return bytes 
Example #7
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.watcher_threads = []
        self.watcher_thread_changes = []
        self.dir_names = []
        self.dir_handles = []
        for i in range(self.num_test_dirs):
            td = tempfile.mktemp("-test-directory-changes-%d" % i)
            os.mkdir(td)
            self.dir_names.append(td)
            hdir = win32file.CreateFile(td, 
                                        ntsecuritycon.FILE_LIST_DIRECTORY,
                                        win32con.FILE_SHARE_READ,
                                        None, # security desc
                                        win32con.OPEN_EXISTING,
                                        win32con.FILE_FLAG_BACKUP_SEMANTICS |
                                        win32con.FILE_FLAG_OVERLAPPED,
                                        None)
            self.dir_handles.append(hdir)

            changes = []
            t = threading.Thread(target=self._watcherThreadOverlapped,
                                 args=(td, hdir, changes))
            t.start()
            self.watcher_threads.append(t)
            self.watcher_thread_changes.append(changes) 
Example #8
Source File: dirmon.py    From dragonfly with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, path):
        if not isinstance(path, basestring):
            raise TypeError("Path argument must be a basestring; instead"
                            " received %r" % (path,))
        self.path = path
        self.handle = win32file.CreateFile(
             self.path,
             0x0001,  # FILE_LIST_DIRECTORY
             win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
             None,
             win32con.OPEN_EXISTING,
             win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED,
             None,
            )
        self.overlapped = win32file.OVERLAPPED()
        self.overlapped.hEvent = win32event.CreateEvent(None, True, 0, None) 
Example #9
Source File: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def connect(self):
            """Attempts to connect to the server, but does not block.

            @return: True if the channel is now connected.
            @rtype: bool
            """
            try:
                if win32pipe.WaitNamedPipe(self.__full_pipe_name, 10) != 0:
                    self.__pipe_handle = win32file.CreateFile(
                        self.__full_pipe_name,
                        win32file.GENERIC_READ,
                        0,
                        None,
                        win32file.OPEN_EXISTING,
                        0,
                        None,
                    )
                    return True
                else:
                    return False
            except pywintypes.error as e:
                if e[0] == winerror.ERROR_FILE_NOT_FOUND:
                    return False
                else:
                    raise e 
Example #10
Source File: test_win32pipe.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testTransactNamedPipeBlockingBuffer(self):
        # Like testTransactNamedPipeBlocking, but a pre-allocated buffer is
        # passed (not really that useful, but it exercises the code path)
        event = threading.Event()
        self.startPipeServer(event)
        open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE

        hpipe = win32file.CreateFile(self.pipename,
                                     open_mode,
                                     0, # no sharing
                                     None, # default security
                                     win32con.OPEN_EXISTING,
                                     0, # win32con.FILE_FLAG_OVERLAPPED,
                                     None)

        # set to message mode.
        win32pipe.SetNamedPipeHandleState(
                        hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)

        buffer = win32file.AllocateReadBuffer(1024)
        hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, None)
        self.failUnlessEqual(got, str2bytes("bar\0foo"))
        event.wait(5)
        self.failUnless(event.isSet(), "Pipe server thread didn't terminate") 
Example #11
Source File: test_win32pipe.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testTransactNamedPipeBlocking(self):
        event = threading.Event()
        self.startPipeServer(event)
        open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE

        hpipe = win32file.CreateFile(self.pipename,
                                     open_mode,
                                     0, # no sharing
                                     None, # default security
                                     win32con.OPEN_EXISTING,
                                     0, # win32con.FILE_FLAG_OVERLAPPED,
                                     None)

        # set to message mode.
        win32pipe.SetNamedPipeHandleState(
                        hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)

        hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None)
        self.failUnlessEqual(got, str2bytes("bar\0foo"))
        event.wait(5)
        self.failUnless(event.isSet(), "Pipe server thread didn't terminate") 
Example #12
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 #13
Source File: dump.py    From Fastir_Collector with GNU General Public License v3.0 6 votes vote down vote up
def csv_export_ram(self):
        """Dump ram using winpmem"""
        hSvc = create_driver_service(self.logger)
        start_service(hSvc, self.logger)
        try:
            fd = win32file.CreateFile(
                "\\\\.\\pmem",
                win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_ATTRIBUTE_NORMAL,
                None)
            try:
                t = time.time()
                image = _Image(fd)
                self.logger.info("Imaging to " + self.output_dir + '\\' + self.computer_name + '_memdump.raw')
                image.DumpWithRead(self.output_dir + '\\' + self.computer_name + '_memdump.raw')
                self.logger.info("Completed in %s seconds" % (time.time() - t))
            finally:
                win32file.CloseHandle(fd)
        finally:
            stop_and_delete_driver_service(hSvc) 
Example #14
Source File: modify_timestamp.py    From BrainDamage with Apache License 2.0 6 votes vote down vote up
def changeTimestamp(path,fileName,daylimit):
    print '[*] Inside changeTimestamp'
    dates = {}
    fileName = os.path.join(path, fileName)
    dates['tdata'] = getDate(fileName,daylimit)
    dates['ctime'] = datetime.utcfromtimestamp(os.path.getctime(fileName))
    
    # print "[*] Original time: ",str(dates['ctime'])
    
    if __use_win_32:
        filehandle = win32file.CreateFile(fileName, win32file.GENERIC_WRITE, 0, None, win32con.OPEN_EXISTING, 0, None)
        win32file.SetFileTime(filehandle, dates['tdata'],dates['tdata'],dates['tdata'])
        filehandle.close()
        print "[*] Timestamps changed!!"
    else:
        os.utime(fileName, (time.mktime(dates['tdata'].utctimetuple()),)*2)
    
    dates['mtime'] = datetime.utcfromtimestamp(os.path.getmtime(fileName))    
    # print "[*] Modified time: ",str(dates['mtime']) 
Example #15
Source File: HID.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        #open file/device
        try:
            handle = win32file.CreateFile(
                self.devicePath,
                win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
                None,  # no security
                win32con.OPEN_EXISTING,
                win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED,
                0
            )
        except pywintypes.error as (errno, function, strerror):
            self.lockObject.release()
            eg.PrintError(self.text.errorOpen + self.deviceName + " (" + strerror + ")")
            return 
Example #16
Source File: win32.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _OpenFileForWrite(self, path):
        try:
            fhandle = self.fhandle = win32file.CreateFile(
                path,
                win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_ATTRIBUTE_NORMAL,
                None)
            self.write_enabled = True
            self._closer = weakref.ref(
                self, lambda x: win32file.CloseHandle(fhandle))

            return fhandle

        except pywintypes.error as e:
            raise IOError("Unable to open %s: %s" % (path, e)) 
Example #17
Source File: win32.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _OpenFileForRead(self, path):
        try:
            fhandle = self.fhandle = win32file.CreateFile(
                path,
                win32file.GENERIC_READ,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_ATTRIBUTE_NORMAL,
                None)

            self._closer = weakref.ref(
                self, lambda x: win32file.CloseHandle(fhandle))

            self.write_enabled = False
            return fhandle

        except pywintypes.error as e:
            raise IOError("Unable to open %s: %s" % (path, e)) 
Example #18
Source File: utils.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def is_open(filename):
    handle = win32file.CreateFile(filename, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING,
                                  win32file.FILE_ATTRIBUTE_NORMAL, 0)
    if handle:
        return True
    else:
        return False 
Example #19
Source File: utils_rawstring.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def get_physical_drive_size(drive="\\\\.\\PhysicalDrive0"):
    """Uses IOCTL to get physical drives size"""
    handle = win32file.CreateFile(drive, 0, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, 0)
    if handle:
        IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000
        info = win32file.DeviceIoControl(handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, '', 24)
        win32file.CloseHandle(handle)
        if info:
            (cyl_lo, cyl_hi, media_type, tps, spt, bps) = struct.unpack('6L', info)
            mediasize = ((cyl_hi << 32) + cyl_lo) * tps * spt * bps
            """print mediasize, 'bytes'
            print mediasize/10**3, 'kbytes'
            print mediasize/10**6, 'Mbytes'
            print mediasize/10**9, 'Gbytes'"""
            return mediasize 
Example #20
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def Connect(self):
        """
        This function tries to connect to the named pipe from AlternateMceIrService.  If it can't connect, it will periodically
        retry until the plugin is stopped or the connection is made.
        """
        self.connecting = True
        #eg.PrintNotice("MCE_Vista: Connect started")
        while self.file is None and self.keepRunning:
            self.SetReceiving(False)
            try:
                self.file = win32file.CreateFile(r'\\.\pipe\MceIr',win32file.GENERIC_READ
                                        |win32file.GENERIC_WRITE,0,None,
                                        win32file.OPEN_EXISTING,win32file.FILE_ATTRIBUTE_NORMAL
                                        |win32file.FILE_FLAG_OVERLAPPED,None)
                if self.sentMessageOnce:
                    eg.PrintNotice("MCE_Vista: Connected to MceIr pipe, started handling IR events")
                    self.plugin.TriggerEvent("Connected")
                    self.sentMessageOnce = False
            except:
                if not self.sentMessageOnce:
                    eg.PrintNotice("MCE_Vista: MceIr pipe is not available, app doesn't seem to be running")
                    eg.PrintNotice("    Will continue to try to connect to MceIr")
                    eg.PrintNotice("    Message = %s"%win32api.FormatMessage(win32api.GetLastError()))
                    self.plugin.TriggerEvent("Disconnected")
                    self.sentMessageOnce = True

                #if self.service and IsServiceStopped(self.service):
                #    eg.PrintNotice("MCE_Vista: MceIr service is stopped, trying to start it...")
                #    StartService(self.service)

                time.sleep(1)
        self.connecting = False
        return 
Example #21
Source File: win32.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def findVolumeGuids():
    DiskExtent = collections.namedtuple(
        'DiskExtent', ['DiskNumber', 'StartingOffset', 'ExtentLength'])
    Volume = collections.namedtuple(
        'Volume', ['Guid', 'MediaType', 'DosDevice', 'Extents'])
    found = []
    h, guid = FindFirstVolume()
    while h and guid:
        #print (guid)
        #print (guid, win32file.GetDriveType(guid),
        #       win32file.QueryDosDevice(guid[4:-1]))
        hVolume = win32file.CreateFile(
            guid[:-1], win32con.GENERIC_READ,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
            None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL,  None)
        extents = []
        driveType = win32file.GetDriveType(guid)
        if driveType in [win32con.DRIVE_REMOVABLE, win32con.DRIVE_FIXED]:
            x = win32file.DeviceIoControl(
                hVolume, winioctlcon.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
                None, 512, None)
            instream = io.BytesIO(x)
            numRecords = struct.unpack('<q', instream.read(8))[0]
            fmt = '<qqq'
            sz = struct.calcsize(fmt)
            while 1:
                b = instream.read(sz)
                if len(b) < sz:
                    break
                rec = struct.unpack(fmt, b)
                extents.append( DiskExtent(*rec) )
        vinfo = Volume(guid, driveType, win32file.QueryDosDevice(guid[4:-1]),
                       extents)
        found.append(vinfo)
        guid = FindNextVolume(h)
    return found 
Example #22
Source File: npipesocket.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def connect(self, address):
        win32pipe.WaitNamedPipe(address, self._timeout)
        try:
            handle = win32file.CreateFile(
                address,
                win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                0,
                None,
                win32file.OPEN_EXISTING,
                cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT,
                0
            )
        except win32pipe.error as e:
            # See Remarks:
            # https://msdn.microsoft.com/en-us/library/aa365800.aspx
            if e.winerror == cERROR_PIPE_BUSY:
                # Another program or thread has grabbed our pipe instance
                # before we got to it. Wait for availability and attempt to
                # connect again.
                win32pipe.WaitNamedPipe(address, RETRY_WAIT_TIMEOUT)
                return self.connect(address)
            raise e

        self.flags = win32pipe.GetNamedPipeInfo(handle)[0]

        self._handle = handle
        self._address = address 
Example #23
Source File: controller.py    From libmelee with GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Connect the controller to the console
        NOTE: Blocks until the other side is ready
        """
        if self._is_dolphin:
            if platform.system() == "Windows":
                # "Create File" in windows is what you use to open a file. Not
                #   create one. Because the windows API is stupid.
                self.pipe = win32file.CreateFile(
                    self.pipe_path,
                    win32file.GENERIC_WRITE,
                    0,
                    None,
                    win32file.OPEN_EXISTING,
                    0,
                    None
                )
            else:
                self.pipe = open(self.pipe_path, "w")
            return True
        else:
            # Remove any extra garbage that might have accumulated in the buffer
            self.tastm32.reset_input_buffer()

            # Send reset command
            self.tastm32.write(b'R')
            cmd = self.tastm32.read(2)
            if cmd != b'\x01R':
                # TODO Better error handling logic here
                print("ERROR: TAStm32 did not reset properly. Try power cycling it.")
                return False
            # Set to gamecube mode
            self.tastm32.write(b'SAG\x80\x00')
            cmd = self.tastm32.read(2)
            self.tastm32.reset_input_buffer()
            if cmd != b'\x01S':
                # TODO Better error handling logic here
                print("ERROR: TAStm32 did not set to GCN mode. Try power cycling it.")
                return False
            return True 
Example #24
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 #25
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testFileTimesTimezones(self):
        if not issubclass(pywintypes.TimeType, datetime.datetime):
            # maybe should report 'skipped', but that's not quite right as
            # there is nothing you can do to avoid it being skipped!
            return
        filename = tempfile.mktemp("-testFileTimes")
        now_utc = win32timezone.utcnow()
        now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local())
        h = win32file.CreateFile(filename,
                                 win32file.GENERIC_READ|win32file.GENERIC_WRITE,
                                 0, None, win32file.CREATE_ALWAYS, 0, 0)
        try:
            win32file.SetFileTime(h, now_utc, now_utc, now_utc)
            ct, at, wt = win32file.GetFileTime(h)
            self.failUnlessEqual(now_local, ct)
            self.failUnlessEqual(now_local, at)
            self.failUnlessEqual(now_local, wt)
            # and the reverse - set local, check against utc
            win32file.SetFileTime(h, now_local, now_local, now_local)
            ct, at, wt = win32file.GetFileTime(h)
            self.failUnlessEqual(now_utc, ct)
            self.failUnlessEqual(now_utc, at)
            self.failUnlessEqual(now_utc, wt)
        finally:
            h.close()
            os.unlink(filename) 
Example #26
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testFilePointer(self):
        # via [ 979270 ] SetFilePointer fails with negative offset

        # Create a file in the %TEMP% directory.
        filename = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )

        f = win32file.CreateFile(filename,
                                win32file.GENERIC_READ|win32file.GENERIC_WRITE,
                                0,
                                None,
                                win32file.CREATE_ALWAYS,
                                win32file.FILE_ATTRIBUTE_NORMAL,
                                0)
        try:
            #Write some data
            data = str2bytes('Some data')
            (res, written) = win32file.WriteFile(f, data)
            
            self.failIf(res)
            self.assertEqual(written, len(data))
            
            #Move at the beginning and read the data
            win32file.SetFilePointer(f, 0, win32file.FILE_BEGIN)
            (res, s) = win32file.ReadFile(f, len(data))
            
            self.failIf(res)
            self.assertEqual(s, data)
            
            #Move at the end and read the data
            win32file.SetFilePointer(f, -len(data), win32file.FILE_END)
            (res, s) = win32file.ReadFile(f, len(data))
            
            self.failIf(res)
            self.failUnlessEqual(s, data)
        finally:
            f.Close()
            os.unlink(filename) 
Example #27
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testMoreFiles(self):
        # Create a file in the %TEMP% directory.
        testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" )
        desiredAccess = win32file.GENERIC_READ | win32file.GENERIC_WRITE
        # Set a flag to delete the file automatically when it is closed.
        fileFlags = win32file.FILE_FLAG_DELETE_ON_CLOSE
        h = win32file.CreateFile( testName, desiredAccess, win32file.FILE_SHARE_READ, None, win32file.CREATE_ALWAYS, fileFlags, 0)
    
        # Write a known number of bytes to the file.
        data = str2bytes("z") * 1025
    
        win32file.WriteFile(h, data)
    
        self.failUnless(win32file.GetFileSize(h) == len(data), "WARNING: Written file does not have the same size as the length of the data in it!")
    
        # Ensure we can read the data back.
        win32file.SetFilePointer(h, 0, win32file.FILE_BEGIN)
        hr, read_data = win32file.ReadFile(h, len(data)+10) # + 10 to get anything extra
        self.failUnless(hr==0, "Readfile returned %d" % hr)

        self.failUnless(read_data == data, "Read data is not what we wrote!")
    
        # Now truncate the file at 1/2 its existing size.
        newSize = len(data)//2
        win32file.SetFilePointer(h, newSize, win32file.FILE_BEGIN)
        win32file.SetEndOfFile(h)
        self.failUnlessEqual(win32file.GetFileSize(h), newSize)
    
        # GetFileAttributesEx/GetFileAttributesExW tests.
        self.failUnlessEqual(win32file.GetFileAttributesEx(testName), win32file.GetFileAttributesExW(testName))

        attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName)
        self.failUnless(size==newSize, 
                        "Expected GetFileAttributesEx to return the same size as GetFileSize()")
        self.failUnless(attr==win32file.GetFileAttributes(testName), 
                        "Expected GetFileAttributesEx to return the same attributes as GetFileAttributes")

        h = None # Close the file by removing the last reference to the handle!

        self.failUnless(not os.path.isfile(testName), "After closing the file, it still exists!") 
Example #28
Source File: test.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def HttpExtensionProc(self, ecb):
        # NOTE: If you use a ThreadPoolExtension, you must still perform
        # this check in HttpExtensionProc - raising the exception from
        # The "Dispatch" method will just cause the exception to be
        # rendered to the browser.
        if self.reload_watcher.change_detected:
            print "Doing reload"
            raise InternalReloadException

        if ecb.GetServerVariable("URL").endswith("test.py"):
            file_flags = win32con.FILE_FLAG_SEQUENTIAL_SCAN  | win32con.FILE_FLAG_OVERLAPPED
            hfile = win32file.CreateFile(__file__, win32con.GENERIC_READ,
                                         0, None, win32con.OPEN_EXISTING,
                                         file_flags, None)
            flags = isapicon.HSE_IO_ASYNC | isapicon.HSE_IO_DISCONNECT_AFTER_SEND | \
                    isapicon.HSE_IO_SEND_HEADERS
            # We pass hFile to the callback simply as a way of keeping it alive
            # for the duration of the transmission
            try:
                ecb.TransmitFile(TransmitFileCallback, hfile,
                                 int(hfile),
                                 "200 OK",
                                 0, 0, None, None, flags)
            except:
                # Errors keep this source file open!
                hfile.Close()
                raise
        else:
            # default response
            ecb.SendResponseHeaders("200 OK", "Content-Type: text/html\r\n\r\n", 0)
            print >> ecb, "<HTML><BODY>"
            print >> ecb, "The root of this site is at", ecb.MapURLToPath("/")
            print >> ecb, "</BODY></HTML>"
            ecb.close()
        return isapicon.HSE_STATUS_SUCCESS 
Example #29
Source File: runas2daemon.py    From pyas2 with GNU General Public License v2.0 4 votes vote down vote up
def windows_event_handler(logger, dir_watch, cond, tasks):
        ACTIONS = {
            1: "Created  ",  # test for printing results
            2: "Deleted  ",
            3: "Updated  ",
            4: "Rename from",
            5: "Rename to",
        }
        FILE_LIST_DIRECTORY = 0x0001
        hDir = win32file.CreateFile(dir_watch['path'],  # to directory
                                    FILE_LIST_DIRECTORY,  # access (read/write) mode
                                    # share mode: FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
                                    win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
                                    None,  # security descriptor
                                    win32con.OPEN_EXISTING,  # how to create
                                    # file attributes: FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED
                                    win32con.FILE_FLAG_BACKUP_SEMANTICS,
                                    None,
                                    )
        # detecting right events is not easy in windows :-(
        # want to detect: new file,  move, drop, rename, write/append to file
        # only FILE_NOTIFY_CHANGE_LAST_WRITE: copy yes, no move
        # for rec=True: event that subdirectory itself is updated (for file deletes in dir)
        while True:
            results = win32file.ReadDirectoryChangesW(hDir,
                                                      8192,  # buffer size was 1024, do not want to miss anything
                                                      False,  # recursive
                                                      win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
                                                      # ~ win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
                                                      # ~ win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
                                                      # ~ win32con.FILE_NOTIFY_CHANGE_SIZE |
                                                      # ~ win32con.FILE_NOTIFY_CHANGE_SECURITY |
                                                      # ~ win32con.FILE_NOTIFY_CHANGE_CREATION |
                                                      # ~ win32con.FILE_NOTIFsY_CHANGE_LAST_ACCESS |
                                                      win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
                                                      None,
                                                      None
                                                      )
            if results:
                # for each incoming event: place route to run in a set. Main thread takes action.
                for action, filename in results:
                    pyas2init.logger.debug(u'Event: %(action)s %(filename)s',
                                           {'action': ACTIONS.get(action, "Unknown"), 'filename': filename})
                for action, filename in results:
                    if action in [1, 3, 5]:  # and fnmatch.fnmatch(filename, dir_watch['filemask']):
                        # ~ if dir_watch['rec'] and os.sep in filename:
                        # ~ continue
                        full_filename = os.path.join(dir_watch['path'], filename)
                        if os.path.isfile(full_filename):
                            cond.acquire()
                            tasks.add((dir_watch['organization'], dir_watch['partner'], full_filename))
                            cond.notify()
                            cond.release()
                            # break       #the route is triggered, do not need to trigger more often
                            # end of windows-specific ############################################## 
Example #30
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.")