Python win32con.FILE_SHARE_READ Examples

The following are 9 code examples of win32con.FILE_SHARE_READ(). 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 win32con , or try the search function .
Example #1
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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: fuctup_comments.py    From darkc0de-old-stuff with GNU General Public License v3.0 4 votes vote down vote up
def watchos():
    #get path or maintain current path of app
    FILE_LIST_DIRECTORY = 0x0001
    try: path_to_watch = myos.get() or "."
    except: path_to_watch = "."
    path_to_watch = os.path.abspath(path_to_watch)

    textbox.insert(END, "Watching %s at %s" % (path_to_watch, time.asctime()) + "\n\n")
    # FindFirstChangeNotification sets up a handle for watching
    #  file changes.
    while 1:

        hDir = win32file.CreateFile (
            path_to_watch,
            FILE_LIST_DIRECTORY,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
            )

        change_handle = win32file.ReadDirectoryChangesW (
            hDir,
            1024,
            True,#Heap Size include_subdirectories,
            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_LAST_WRITE |
            win32con.FILE_NOTIFY_CHANGE_SECURITY,
            None,
            None
            )

        # Loop forever, listing any file changes. The WaitFor... will
        #  time out every half a second allowing for keyboard interrupts
        #  to terminate the loop.
        ACTIONS = {
            1 : "Created",
            2 : "Deleted",
            3 : "Updated",
            4 : "Renamed from something",
            5 : "Renamed to something"
            }
        results = change_handle
        for action, files in results:
            full_filename = os.path.join(path_to_watch, files)
            theact = ACTIONS.get(action, "Unknown")
            textbox.insert(END, str(full_filename) + "\t" + str(theact) +"\n")