Python win32api 模块,GetTempPath() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用win32api.GetTempPath()

项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def Flush(self, whatsthis=0):
        print "Flush" + str(whatsthis)
        fname = os.path.join(win32api.GetTempPath(), "persist.doc")
        open(fname, "wb").write(self.data)
        return S_OK
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def Flush(self, whatsthis=0):
        print "Flush" + str(whatsthis)
        fname = os.path.join(win32api.GetTempPath(), "persist.doc")
        open(fname, "wb").write(self.data)
        return S_OK
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def testRecord(self):
        d = ds.DirectSoundCaptureCreate(None, None)

        sdesc = ds.DSCBUFFERDESC()
        sdesc.dwBufferBytes = 352800 # 2 seconds
        sdesc.lpwfxFormat = pywintypes.WAVEFORMATEX()
        sdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM
        sdesc.lpwfxFormat.nChannels = 2
        sdesc.lpwfxFormat.nSamplesPerSec = 44100
        sdesc.lpwfxFormat.nAvgBytesPerSec = 176400
        sdesc.lpwfxFormat.nBlockAlign = 4
        sdesc.lpwfxFormat.wBitsPerSample = 16

        buffer = d.CreateCaptureBuffer(sdesc)

        event = win32event.CreateEvent(None, 0, 0, None)
        notify = buffer.QueryInterface(ds.IID_IDirectSoundNotify)

        notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP, event))

        buffer.Start(0)

        win32event.WaitForSingleObject(event, -1)
        event.Close()

        data = buffer.Update(0, 352800)
        fname=os.path.join(win32api.GetTempPath(), 'test_directsound_record.wav')
        f = open(fname, 'wb')
        f.write(wav_header_pack(sdesc.lpwfxFormat, 352800))
        f.write(data)
        f.close()
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def BackupClearLog(logType):
    datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
    fileExists = 1
    retry = 0
    while fileExists:
        if retry == 0:
            index = ""
        else:
            index = "-%d" % retry
        try:
            fname = os.path.join(win32api.GetTempPath(), "%s%s-%s" % (datePrefix, index, logType) + ".evt")
            os.stat(fname)
        except os.error:
            fileExists = 0
        retry = retry + 1
    # OK - have unique file name.
    try:
        hlog = win32evtlog.OpenEventLog(None, logType)
    except win32evtlogutil.error, details:
        print "Could not open the event log", details
        return
    try:
        if win32evtlog.GetNumberOfEventLogRecords(hlog)==0:
            print "No records in event log %s - not backed up" % logType
            return
        win32evtlog.ClearEventLog(hlog, fname)
        print "Backed up %s log to %s" % (logType, fname)
    finally:
        win32evtlog.CloseEventLog(hlog)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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!")
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def Flush(self, whatsthis=0):
        print "Flush" + str(whatsthis)
        fname = os.path.join(win32api.GetTempPath(), "persist.doc")
        open(fname, "wb").write(self.data)
        return S_OK
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def testRecord(self):
        d = ds.DirectSoundCaptureCreate(None, None)

        sdesc = ds.DSCBUFFERDESC()
        sdesc.dwBufferBytes = 352800 # 2 seconds
        sdesc.lpwfxFormat = pywintypes.WAVEFORMATEX()
        sdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM
        sdesc.lpwfxFormat.nChannels = 2
        sdesc.lpwfxFormat.nSamplesPerSec = 44100
        sdesc.lpwfxFormat.nAvgBytesPerSec = 176400
        sdesc.lpwfxFormat.nBlockAlign = 4
        sdesc.lpwfxFormat.wBitsPerSample = 16

        buffer = d.CreateCaptureBuffer(sdesc)

        event = win32event.CreateEvent(None, 0, 0, None)
        notify = buffer.QueryInterface(ds.IID_IDirectSoundNotify)

        notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP, event))

        buffer.Start(0)

        win32event.WaitForSingleObject(event, -1)
        event.Close()

        data = buffer.Update(0, 352800)
        fname=os.path.join(win32api.GetTempPath(), 'test_directsound_record.wav')
        f = open(fname, 'wb')
        f.write(wav_header_pack(sdesc.lpwfxFormat, 352800))
        f.write(data)
        f.close()
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def BackupClearLog(logType):
    datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
    fileExists = 1
    retry = 0
    while fileExists:
        if retry == 0:
            index = ""
        else:
            index = "-%d" % retry
        try:
            fname = os.path.join(win32api.GetTempPath(), "%s%s-%s" % (datePrefix, index, logType) + ".evt")
            os.stat(fname)
        except os.error:
            fileExists = 0
        retry = retry + 1
    # OK - have unique file name.
    try:
        hlog = win32evtlog.OpenEventLog(None, logType)
    except win32evtlogutil.error as details:
        print("Could not open the event log", details)
        return
    try:
        if win32evtlog.GetNumberOfEventLogRecords(hlog)==0:
            print("No records in event log %s - not backed up" % logType)
            return
        win32evtlog.ClearEventLog(hlog, fname)
        print("Backed up %s log to %s" % (logType, fname))
    finally:
        win32evtlog.CloseEventLog(hlog)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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!")
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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()
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def Flush(self, whatsthis=0):
        print("Flush" + str(whatsthis))
        fname = os.path.join(win32api.GetTempPath(), "persist.doc")
        open(fname, "wb").write(self.data)
        return S_OK
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def OnSaveDocument( self, fileName ):
        win32ui.SetStatusText("Saving file...",1)
        # rename to bak if required.
        dir, basename = os.path.split(fileName)
        if self.bakFileType==BAK_DOT_BAK:
            bakFileName=dir+'\\'+os.path.splitext(basename)[0]+'.bak'
        elif self.bakFileType==BAK_DOT_BAK_TEMP_DIR:
            bakFileName=win32api.GetTempPath()+'\\'+os.path.splitext(basename)[0]+'.bak'
        elif self.bakFileType==BAK_DOT_BAK_BAK_DIR:
            tempPath=os.path.join(win32api.GetTempPath(),'bak')
            try:
                os.mkdir(tempPath,0)
            except os.error:
                pass
            bakFileName=os.path.join(tempPath,basename)
        try:
            os.unlink(bakFileName)  # raise NameError if no bakups wanted.
        except (os.error, NameError):
            pass
        try:
            # Do a copy as it might be on different volumes,
            # and the file may be a hard-link, causing the link
            # to follow the backup.
            shutil.copy2(fileName, bakFileName)
        except (os.error, NameError, IOError):
            pass
        try:
            self.SaveFile(fileName)
        except IOError, details:
            win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details)
            return 0
        except (UnicodeEncodeError, LookupError), details:
            rc = win32ui.MessageBox("Encoding failed: \r\n%s"%details +
                    '\r\nPlease add desired source encoding as first line of file, eg \r\n' +
                    '# -*- coding: mbcs -*-\r\n\r\n' +
                    'If you continue, the file will be saved as binary and will\r\n' +
                    'not be valid in the declared encoding.\r\n\r\n' +
                    'Save the file as binary with an invalid encoding?',
                    "File save failed",
                    win32con.MB_YESNO | win32con.MB_DEFBUTTON2)
            if rc==win32con.IDYES:
                try:
                    self.SaveFile(fileName, encoding="latin-1")
                except IOError, details:
                    win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details)
                    return 0
            else:
                return 0
        self.SetModifiedFlag(0) # No longer dirty
        self.bDeclinedReload = 0 # They probably want to know if it changes again!
        win32ui.AddToRecentFileList(fileName)
        self.SetPathName(fileName)
        win32ui.SetStatusText("Ready")
        self._DocumentStateChanged()
        return 1
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def OnSaveDocument( self, fileName ):
        win32ui.SetStatusText("Saving file...",1)
        # rename to bak if required.
        dir, basename = os.path.split(fileName)
        if self.bakFileType==BAK_DOT_BAK:
            bakFileName=dir+'\\'+os.path.splitext(basename)[0]+'.bak'
        elif self.bakFileType==BAK_DOT_BAK_TEMP_DIR:
            bakFileName=win32api.GetTempPath()+'\\'+os.path.splitext(basename)[0]+'.bak'
        elif self.bakFileType==BAK_DOT_BAK_BAK_DIR:
            tempPath=os.path.join(win32api.GetTempPath(),'bak')
            try:
                os.mkdir(tempPath,0)
            except os.error:
                pass
            bakFileName=os.path.join(tempPath,basename)
        try:
            os.unlink(bakFileName)  # raise NameError if no bakups wanted.
        except (os.error, NameError):
            pass
        try:
            # Do a copy as it might be on different volumes,
            # and the file may be a hard-link, causing the link
            # to follow the backup.
            shutil.copy2(fileName, bakFileName)
        except (os.error, NameError, IOError):
            pass
        try:
            self.SaveFile(fileName)
        except IOError as details:
            win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details)
            return 0
        except (UnicodeEncodeError, LookupError) as details:
            rc = win32ui.MessageBox("Encoding failed: \r\n%s"%details +
                    '\r\nPlease add desired source encoding as first line of file, eg \r\n' +
                    '# -*- coding: mbcs -*-\r\n\r\n' +
                    'If you continue, the file will be saved as binary and will\r\n' +
                    'not be valid in the declared encoding.\r\n\r\n' +
                    'Save the file as binary with an invalid encoding?',
                    "File save failed",
                    win32con.MB_YESNO | win32con.MB_DEFBUTTON2)
            if rc==win32con.IDYES:
                try:
                    self.SaveFile(fileName, encoding="latin-1")
                except IOError as details:
                    win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details)
                    return 0
            else:
                return 0
        self.SetModifiedFlag(0) # No longer dirty
        self.bDeclinedReload = 0 # They probably want to know if it changes again!
        win32ui.AddToRecentFileList(fileName)
        self.SetPathName(fileName)
        win32ui.SetStatusText("Ready")
        self._DocumentStateChanged()
        return 1