Python win32api.GetTempPath() Examples

The following are 11 code examples of win32api.GetTempPath(). 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 win32api , or try the search function .
Example #1
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 #2
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testEmptyDir(self):
        test_path = os.path.join(win32api.GetTempPath(), "win32file_test_directory")
        try:
            # Note: previously used shutil.rmtree, but when looking for
            # reference count leaks, that function showed leaks!  os.rmdir
            # doesn't have that problem.
            os.rmdir(test_path)
        except os.error:
            pass
        os.mkdir(test_path)
        try:
            num = 0
            for i in win32file.FindFilesIterator(os.path.join(test_path, "*")):
                num += 1
            # Expecting "." and ".." only
            self.failUnlessEqual(2, num)
        finally:
            os.rmdir(test_path) 
Example #3
Source File: backupEventLog.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_stdinReader_unicodeArgs(self):
        """
        Pass L{unicode} args to L{_test_stdinReader}.
        """
        import win32api

        pyExe = FilePath(sys.executable)._asTextPath()
        args = [pyExe, u"-u", u"-m", u"twisted.test.process_stdinreader"]
        env = properEnv
        pythonPath = os.pathsep.join(sys.path)
        if isinstance(pythonPath, bytes):
            pythonPath = pythonPath.decode(sys.getfilesystemencoding())
        env[u"PYTHONPATH"] = pythonPath
        path = win32api.GetTempPath()
        if isinstance(path, bytes):
            path = path.decode(sys.getfilesystemencoding())
        d = self._test_stdinReader(pyExe, args, env, path)
        return d 
Example #5
Source File: platform.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def get_temp_dir():
    shellvars = ['${TMP}', '${TEMP}']
    dir_root = get_dir_root(shellvars, default_to_home=False)

    #this method is preferred to the envvars
    if os.name == 'nt':
        try_dir_root = win32api.GetTempPath()
        if try_dir_root is not None:
            dir_root = try_dir_root

    if dir_root is None:
        try_dir_root = None
        if os.name == 'nt':
            # this should basically never happen. GetTempPath always returns something
            try_dir_root = r'C:\WINDOWS\Temp'
        elif os.name == 'posix':
            try_dir_root = '/tmp'
        if (try_dir_root is not None and
            os.path.isdir(try_dir_root) and
            os.access(try_dir_root, os.R_OK|os.W_OK)):
            dir_root = try_dir_root
    return dir_root 
Example #6
Source File: ds_test.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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() 
Example #7
Source File: document.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 
Example #8
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 #9
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 #10
Source File: testPersist.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 
Example #11
Source File: test_process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_stdinReader_bytesArgs(self):
        """
        Pass L{bytes} args to L{_test_stdinReader}.
        """
        import win32api

        pyExe = FilePath(sys.executable)._asBytesPath()
        args = [pyExe, b"-u", b"-m", b"twisted.test.process_stdinreader"]
        env = bytesEnviron()
        env[b"PYTHONPATH"] = os.pathsep.join(sys.path).encode(
                                             sys.getfilesystemencoding())
        path = win32api.GetTempPath()
        path = path.encode(sys.getfilesystemencoding())
        d = self._test_stdinReader(pyExe, args, env, path)
        return d