# hrmph - 3.3 throws: TypeError: '_NamespacePath' object does not support indexing # attempting to get __path__[0] - but I can't quickly repro this stand-alone. # Work around it by using an iterator. __gen_path__ = next(iter(sys.modules["win32com.gen_py"].__path__)) except ImportError: # If a win32com\gen_py directory already exists, then we use it # (gencache doesn't insist it have an __init__, but our __import__ # above does! __gen_path__ = os.path.abspath(os.path.join(__path__[0], "gen_py")) if not os.path.isdir(__gen_path__): # We used to dynamically create a directory under win32com - # but this sucks. If the dir doesn't already exist, we we # create a version specific directory under the user temp # directory. __gen_path__ = os.path.join( win32api.GetTempPath(), "gen_py", "%d.%d" % (sys.version_info[0], sys.version_info[1])) # we must have a __gen_path__, but may not have a gen_py module - # set that up. if "win32com.gen_py" not in sys.modules: # Create a "win32com.gen_py", but with a custom __path__ import imp gen_py = imp.new_module("win32com.gen_py") gen_py.__path__ = [__gen_path__] sys.modules[gen_py.__name__] = gen_py del imp gen_py = sys.modules["win32com.gen_py"] # get rid of these for module users
import os import win32security, win32file, win32api, ntsecuritycon, win32con from security_enums import TRUSTEE_TYPE, TRUSTEE_FORM, ACE_FLAGS, ACCESS_MODE fname = os.path.join(win32api.GetTempPath(), "win32security_test.txt") f = open(fname, "w") f.write("Hello from Python\n") f.close() print("Testing on file", fname) new_privs = ( (win32security.LookupPrivilegeValue('', ntsecuritycon.SE_SECURITY_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', ntsecuritycon.SE_SHUTDOWN_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', ntsecuritycon.SE_RESTORE_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', ntsecuritycon.SE_TAKE_OWNERSHIP_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', ntsecuritycon.SE_CREATE_PERMANENT_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', 'SeEnableDelegationPrivilege'), win32con.SE_PRIVILEGE_ENABLED) ##doesn't seem to be in ntsecuritycon.py ? ) ph = win32api.GetCurrentProcess() th = win32security.OpenProcessToken( ph, win32security.TOKEN_ALL_ACCESS) ##win32con.TOKEN_ADJUST_PRIVILEGES) win32security.AdjustTokenPrivileges(th, 0, new_privs)
def CreateTestAccessDatabase(dbname=None): # Creates a test access database - returns the filename. if dbname is None: dbname = os.path.join(win32api.GetTempPath(), "COMTestSuiteTempDatabase.mdb") access = Dispatch("Access.Application") dbEngine = access.DBEngine workspace = dbEngine.Workspaces(0) try: os.unlink(dbname) except os.error: print( "WARNING - Unable to delete old test database - expect a COM exception RSN!" ) newdb = workspace.CreateDatabase(dbname, constants.dbLangGeneral, constants.dbEncrypt) # Create one test table. table = newdb.CreateTableDef("Test Table 1") table.Fields.Append(table.CreateField("First Name", constants.dbText)) table.Fields.Append(table.CreateField("Last Name", constants.dbText)) index = table.CreateIndex("UniqueIndex") index.Fields.Append(index.CreateField("First Name")) index.Fields.Append(index.CreateField("Last Name")) index.Unique = -1 table.Indexes.Append(index) newdb.TableDefs.Append(table) # Create a second test table. table = newdb.CreateTableDef("Test Table 2") table.Fields.Append(table.CreateField("First Name", constants.dbText)) table.Fields.Append(table.CreateField("Last Name", constants.dbText)) newdb.TableDefs.Append(table) # Create a relationship between them relation = newdb.CreateRelation("TestRelationship") relation.Table = "Test Table 1" relation.ForeignTable = "Test Table 2" field = relation.CreateField("First Name") field.ForeignName = "First Name" relation.Fields.Append(field) field = relation.CreateField("Last Name") field.ForeignName = "Last Name" relation.Fields.Append(field) relation.Attributes = constants.dbRelationDeleteCascade + constants.dbRelationUpdateCascade newdb.Relations.Append(relation) # Finally we can add some data to the table. tab1 = newdb.OpenRecordset("Test Table 1") tab1.AddNew() tab1.Fields("First Name").Value = "Mark" tab1.Fields("Last Name").Value = "Hammond" tab1.Update() tab1.MoveFirst() # We do a simple bookmark test which tests our optimized VT_SAFEARRAY|VT_UI1 support. # The bookmark will be a buffer object - remember it for later. bk = tab1.Bookmark # Add a second record. tab1.AddNew() tab1.Fields("First Name").Value = "Second" tab1.Fields("Last Name").Value = "Person" tab1.Update() # Reset the bookmark to the one we saved. # But first check the test is actually doing something! tab1.MoveLast() if tab1.Fields("First Name").Value != "Second": raise RuntimeError( "Unexpected record is last - makes bookmark test pointless!") tab1.Bookmark = bk if tab1.Bookmark != bk: raise RuntimeError("The bookmark data is not the same") if tab1.Fields("First Name").Value != "Mark": raise RuntimeError( "The bookmark did not reset the record pointer correctly") return dbname
# hrmph - 3.3 throws: TypeError: '_NamespacePath' object does not support indexing # attempting to get __path__[0] - but I can't quickly repro this stand-alone. # Work around it by using an iterator. __gen_path__ = next(iter(sys.modules["win32com.gen_py"].__path__)) except ImportError: # If a win32com\gen_py directory already exists, then we use it # (gencache doesn't insist it have an __init__, but our __import__ # above does! __gen_path__ = os.path.abspath(os.path.join(__path__[0], "gen_py")) if not os.path.isdir(__gen_path__): # We used to dynamically create a directory under win32com - # but this sucks. If the dir doesn't already exist, we we # create a version specific directory under the user temp # directory. __gen_path__ = os.path.join( win32api.GetTempPath(), "gen_py", "%d.%d" % (sys.version_info[0], sys.version_info[1]), ) # we must have a __gen_path__, but may not have a gen_py module - # set that up. if "win32com.gen_py" not in sys.modules: # Create a "win32com.gen_py", but with a custom __path__ import types gen_py = types.ModuleType("win32com.gen_py") gen_py.__path__ = [__gen_path__] sys.modules[gen_py.__name__] = gen_py del types gen_py = sys.modules["win32com.gen_py"]
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
import win32security, win32api, win32con, win32process fname, tmp = win32api.GetTempFileName(win32api.GetTempPath(), 'tmp') print fname ## You need SE_RESTORE_NAME to be able to set the owner of a security descriptor to anybody ## other than yourself or your primary group. Most admin logins don't have it by default, so ## enabling it may fail new_privs = ( (win32security.LookupPrivilegeValue('', win32security.SE_SECURITY_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', win32security.SE_TCB_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_SHUTDOWN_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', win32security.SE_RESTORE_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_TAKE_OWNERSHIP_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', win32security.SE_CREATE_PERMANENT_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', win32security.SE_ENABLE_DELEGATION_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', win32security.SE_CHANGE_NOTIFY_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_DEBUG_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '', win32security.SE_PROF_SINGLE_PROCESS_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_SYSTEM_PROFILE_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue( '',
def testit(self): fname, tmp = win32api.GetTempFileName(win32api.GetTempPath(), "stg") m = storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE ## file, mode, format, attrs (always 0), IID (IStorage or IPropertySetStorage, storage options(only used with STGFMT_DOCFILE) pss = pythoncom.StgOpenStorageEx(fname, m, storagecon.STGFMT_FILE, 0, pythoncom.IID_IPropertySetStorage) ### {"Version":2,"reserved":0,"SectorSize":512,"TemplateFile":u'somefilename'}) ## FMTID_SummaryInformation FMTID_DocSummaryInformation FMTID_UserDefinedProperties psuser = pss.Create( pythoncom.FMTID_UserDefinedProperties, pythoncom.IID_IPropertySetStorage, storagecon.PROPSETFLAG_DEFAULT, storagecon.STGM_READWRITE | storagecon.STGM_CREATE | storagecon.STGM_SHARE_EXCLUSIVE, ) ## its very picky about flag combinations! psuser.WriteMultiple((3, 4), ("hey", "bubba")) psuser.WritePropertyNames((3, 4), ("property3", "property4")) expected_summaries = [] expected_summaries.append(("property3", 3, pythoncom.VT_BSTR)) expected_summaries.append(("property4", 4, pythoncom.VT_BSTR)) psuser = None pssum = pss.Create( pythoncom.FMTID_SummaryInformation, pythoncom.IID_IPropertySetStorage, storagecon.PROPSETFLAG_DEFAULT, storagecon.STGM_READWRITE | storagecon.STGM_CREATE | storagecon.STGM_SHARE_EXCLUSIVE, ) pssum.WriteMultiple( (storagecon.PIDSI_AUTHOR, storagecon.PIDSI_COMMENTS), ("me", "comment")) pssum = None pss = None ## doesn't seem to be a close or release method, and you can't even reopen it from the same process until previous object is gone pssread = pythoncom.StgOpenStorageEx( fname, storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE, storagecon.STGFMT_FILE, 0, pythoncom.IID_IPropertySetStorage, ) found_summaries = [] for psstat in pssread: ps = pssread.Open( psstat[0], storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE) for p in ps: p_val = ps.ReadMultiple((p[1], ))[0] if (p[1] == storagecon.PIDSI_AUTHOR and p_val == "me") or (p[1] == storagecon.PIDSI_COMMENTS and p_val == "comment"): pass else: self.fail("Uxexpected property %s/%s" % (p, p_val)) ps = None ## FMTID_UserDefinedProperties can't exist without FMTID_DocSummaryInformation, and isn't returned independently from Enum ## also can't be open at same time if psstat[0] == pythoncom.FMTID_DocSummaryInformation: ps = pssread.Open( pythoncom.FMTID_UserDefinedProperties, storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE, ) for p in ps: found_summaries.append(p) ps = None psread = None expected_summaries.sort() found_summaries.sort() self.assertEqual(expected_summaries, found_summaries)
def Path_TempDirectory(self): #ifdef __WXMSW__ #TCHAR szPathBuffer[MAX_PATH] = ""; #GetTempPath(MAX_PATH, szPathBuffer); return win32api.GetTempPath()
def GetTempFilePath(self, tempfilepath): output_temp = win32api.GetTempPath() + os.path.basename(tempfilepath) output_temp = output_temp.replace('\\', '\\\\') return output_temp
## print fnamein, fnameout, buflen f.write(input_buffer) ## python 2.3 throws an error if return value is a plain int return winerror.ERROR_SUCCESS def WriteCallback(output_buffer, data, buflen): fnamebackup, fnameout, f = data file_data = f.read(buflen) ## returning 0 as len terminates WriteEncryptedFileRaw output_len = len(file_data) output_buffer[:output_len] = file_data return winerror.ERROR_SUCCESS, output_len tmp_dir = win32api.GetTempPath() dst_dir = win32api.GetTempFileName(tmp_dir, 'oef')[0] os.remove(dst_dir) os.mkdir(dst_dir) print 'Destination dir:', dst_dir ## create an encrypted file fname = win32api.GetTempFileName(dst_dir, 'ref')[0] print 'orig file:', fname f = open(fname, 'w') f.write('xxxxxxxxxxxxxxxx\n' * 32768) f.close() ## add a couple of extra data streams f = open(fname + ':stream_y', 'w') f.write('yyyyyyyyyyyyyyyy\n' * 32768) f.close()
def check_shortpathname(fn): lfn = win32api.GetLongPathNameW(fn) fn = os.path.normcase(fn) lfn = os.path.normcase(lfn) if lfn != fn: print("ShortPathName: Expected %s, got %s" % (fn, lfn)) raise SystemExit(-1) print("sys.executable:", ascii(sys.executable)) if not os.path.exists(sys.executable): raise SystemExit("sys.executable does not exist.") check_shortpathname(sys.executable) print("sys.argv[0]:", ascii(sys.argv[0])) if not os.path.exists(sys.argv[0]): raise SystemExit("sys.argv[0] does not exist.") check_shortpathname(sys.argv[0]) print("sys._MEIPASS:"******"sys._MEIPASS does not exist.") tmp = os.path.normcase(win32api.GetTempPath()) if os.path.normcase(win32api.GetLongPathNameW(tmp)) == tmp: # Test only if TempPath is not a short path. This might happen if e.g # TMP=c:\users\runner~1\appdata\local\temp, since the username is too long check_shortpathname(sys._MEIPASS)
def tmpDir(): #pylint: disable=F0401 import win32api return win32api.GetTempPath()
def tmpDir(): import win32api return win32api.GetTempPath()
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 print(sdesc) print(d) 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) 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()
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
## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams import win32file, win32api, win32con, win32security, ntsecuritycon from win32com import storagecon import pythoncom, pywintypes import struct, traceback all_sd_info=win32security.DACL_SECURITY_INFORMATION|win32security.DACL_SECURITY_INFORMATION| \ win32security.OWNER_SECURITY_INFORMATION|win32security.GROUP_SECURITY_INFORMATION tempdir = win32api.GetTempPath() tempfile = win32api.GetTempFileName(tempdir, 'bkr')[0] outfile = win32api.GetTempFileName(tempdir, 'out')[0] print 'Filename:', tempfile, 'Output file:', outfile f = open(tempfile, 'w') f.write('some random junk' + 'x' * 100) f.close() ## add a couple of alternate data streams f = open(tempfile + ':streamdata', 'w') f.write('data written to alternate stream' + 'y' * 100) f.close() f = open(tempfile + ':anotherstream', 'w') f.write('z' * 100) f.close() ## add Summary Information, which is stored as a separate stream m = storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE | storagecon.STGM_DIRECT pss = pythoncom.StgOpenStorageEx(tempfile, m, storagecon.STGFMT_FILE, 0,
def demo(): """ Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION: typedef struct _TXFS_CREATE_MINIVERSION_INFO{ USHORT StructureVersion; USHORT StructureLength; ULONG BaseVersion; USHORT MiniVersion;} """ buf_fmt = 'HHLH0L' ## buffer size must include struct padding buf_size = struct.calcsize(buf_fmt) tempdir = win32api.GetTempPath() tempfile = win32api.GetTempFileName(tempdir, 'cft')[0] print("Demonstrating transactions on tempfile", tempfile) f = open(tempfile, 'w') f.write('This is original file.\n') f.close() trans = win32transaction.CreateTransaction( Description='Test creating miniversions of a file') hfile = win32file.CreateFileW( tempfile, win32con.GENERIC_READ | win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans) win32file.WriteFile(hfile, str2bytes('This is first miniversion.\n')) buf = win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None) struct_ver, struct_len, base_ver, ver_1 = struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) win32file.WriteFile(hfile, str2bytes('This is second miniversion!\n')) buf = win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None) struct_ver, struct_len, base_ver, ver_2 = struct.unpack(buf_fmt, buf) hfile.Close() ## miniversions can't be opened with write access hfile_0 = win32file.CreateFileW(tempfile, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, MiniVersion=base_ver) print('version:', base_ver, win32file.ReadFile(hfile_0, 100)) hfile_0.Close() hfile_1 = win32file.CreateFileW(tempfile, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, MiniVersion=ver_1) print('version:', ver_1, win32file.ReadFile(hfile_1, 100)) hfile_1.Close() hfile_2 = win32file.CreateFileW(tempfile, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, MiniVersion=ver_2) print('version:', ver_2, win32file.ReadFile(hfile_2, 100)) hfile_2.Close() ## MiniVersions are destroyed when transaction is committed or rolled back win32transaction.CommitTransaction(trans) os.unlink(tempfile)