def LocatePythonServiceExe(exeName = None): if not exeName and hasattr(sys, "frozen"): # If py2exe etc calls this with no exeName, default is current exe. return sys.executable # Try and find the specified EXE somewhere. If specifically registered, # use it. Otherwise look down sys.path, and the global PATH environment. if exeName is None: if os.path.splitext(win32service.__file__)[0].endswith("_d"): exeName = "PythonService_d.exe" else: exeName = "PythonService.exe" # See if it exists as specified if os.path.isfile(exeName): return win32api.GetFullPathName(exeName) baseName = os.path.splitext(os.path.basename(exeName))[0] try: exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\%s\\%s" % (baseName, sys.winver)) if os.path.isfile(exeName): return exeName raise RuntimeError("The executable '%s' is registered as the Python " \ "service exe, but it does not exist as specified" \ % exeName) except win32api.error: # OK - not there - lets go a-searchin' for path in [sys.prefix] + sys.path: look = os.path.join(path, exeName) if os.path.isfile(look): return win32api.GetFullPathName(look) # Try the global Path. try: return win32api.SearchPath(None, exeName)[0] except win32api.error: msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % (exeName, exeName) raise error(msg)
def BuildFileList(spec, local, recurse, filter, filter_args, recursed_path=""): files = [] if isdir(spec, local): path = spec raw_spec = "*" else: path, raw_spec = os.path.split(spec) if recurse: # Need full scan, to get sub-direcetories. infos = FindFiles(os.path.join(path, "*"), local) else: infos = FindFiles(os.path.join(path, raw_spec), local) for info in infos: src_name = str(info[8]) full_src_name = os.path.join(path, src_name) if local: # Can't do this for CE! full_src_name = win32api.GetFullPathName(full_src_name) if isdir(full_src_name, local): if recurse and src_name not in ['.', '..']: new_spec = os.path.join(full_src_name, raw_spec) files = files + BuildFileList(new_spec, local, 1, filter, filter_args, os.path.join(recursed_path, src_name)) if fnmatch.fnmatch(src_name, raw_spec): rel_name = os.path.join(recursed_path, src_name) filter_data = filter(full_src_name, rel_name, info, local, filter_args) if filter_data is not None: files.append((full_src_name, info, filter_data)) return files
def Demo(): import sys, win32api docName = None if len(sys.argv) > 1: docName = win32api.GetFullPathName(sys.argv[1]) OleTemplate().OpenDocumentFile(None)
def TestExplorerEvents(): iexplore = win32com.client.DispatchWithEvents( "InternetExplorer.Application", ExplorerEvents) thread = win32api.GetCurrentThreadId() print('TestExplorerEvents created IE object on thread %d'%thread) iexplore.Visible = 1 try: iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) except pythoncom.com_error as details: print("Warning - could not open the tests HTML file", details) # In this free-threaded example, we can simply wait until an event has # been set - we will give it 2 seconds before giving up. rc = win32event.WaitForSingleObject(iexplore.event, 2000) if rc != win32event.WAIT_OBJECT_0: print("Document load event FAILED to fire!!!") iexplore.Quit() # Now we can do the same thing to wait for exit! # Although Quit generates events, in this free-threaded world we # do *not* need to run any message pumps. rc = win32event.WaitForSingleObject(iexplore.event, 2000) if rc != win32event.WAIT_OBJECT_0: print("OnQuit event FAILED to fire!!!") iexplore = None print("Finished the IE event sample!")
def testHost(self): file = win32api.GetFullPathName( os.path.join(win32com.axscript.__path__[0], "test\\testHost.py")) cmd = '%s "%s"' % (win32api.GetModuleFileName(0), file) if verbose: print("Testing Python Scripting host") win32com.test.util.ExecuteShellCommand(cmd, self)
def checkextensions(unknown, extra_inis): # Create a table of frozen extensions defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini") if not os.path.isfile(defaultMapName): sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found" % mapFileName) else: # must go on end, so other inis can override. extra_inis.append(defaultMapName) ret = [] for mod in unknown: for ini in extra_inis: # print "Looking for", mod, "in", win32api.GetFullPathName(ini),"...", if win32api and not os.path.isabs(ini): ini = win32api.GetFullPathName(ini) defn = get_extension_defn( mod, ini ) if defn is not None: # print "Yay - found it!" ret.append( defn ) break # print "Nope!" else: # For not broken! sys.stderr.write("No definition of module %s in any specified map file.\n" % (mod)) return ret
def setUp(self): file = win32api.GetFullPathName( os.path.join(win32com.axscript.client.__path__[0], "pyscript.py")) from win32com.test.util import RegisterPythonServer self.verbose = verbose RegisterPythonServer(file, "python", verbose=self.verbose)
def TestExplorerEvents(): iexplore = win32com.client.DispatchWithEvents( "InternetExplorer.Application", ExplorerEvents) thread = win32api.GetCurrentThreadId() print('TestExplorerEvents created IE object on thread %d' % thread) iexplore.Visible = 1 try: iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) except pythoncom.com_error as details: print("Warning - could not open the test HTML file", details) # Wait for the event to be signalled while pumping messages. if not WaitWhileProcessingMessages(iexplore.event): print("Document load event FAILED to fire!!!") iexplore.Quit() # # Give IE a chance to shutdown, else it can get upset on fast machines. # Note, Quit generates events. Although this test does NOT catch them # it is NECESSARY to pump messages here instead of a sleep so that the Quit # happens properly! if not WaitWhileProcessingMessages(iexplore.event): print("OnQuit event FAILED to fire!!!") iexplore = None
def testCScript(self): file = win32api.GetFullPathName( os.path.join(win32com.axscript.__path__[0], "Demos\\Client\\wsh\\test.pys")) cmd = 'cscript.exe "%s"' % (file) if verbose: print("Testing Windows Scripting host with Python script") win32com.test.util.ExecuteShellCommand(cmd, self)
def InstallPerfmonForService(serviceName, iniName, dllName=None): # If no DLL name, look it up in the INI file name if not dllName: # May be empty string! dllName = win32api.GetProfileVal("Python", "dll", "", iniName) # Still not found - look for the standard one in the same dir as win32service.pyd if not dllName: try: tryName = os.path.join( os.path.split(win32service.__file__)[0], "perfmondata.dll" ) if os.path.isfile(tryName): dllName = tryName except AttributeError: # Frozen app? - anyway, can't find it! pass if not dllName: raise ValueError("The name of the performance DLL must be available") dllName = win32api.GetFullPathName(dllName) # Now setup all the required "Performance" entries. hkey = win32api.RegOpenKey( win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS, ) try: subKey = win32api.RegCreateKey(hkey, "Performance") try: win32api.RegSetValueEx(subKey, "Library", 0, win32con.REG_SZ, dllName) win32api.RegSetValueEx( subKey, "Open", 0, win32con.REG_SZ, "OpenPerformanceData" ) win32api.RegSetValueEx( subKey, "Close", 0, win32con.REG_SZ, "ClosePerformanceData" ) win32api.RegSetValueEx( subKey, "Collect", 0, win32con.REG_SZ, "CollectPerformanceData" ) finally: win32api.RegCloseKey(subKey) finally: win32api.RegCloseKey(hkey) # Now do the "Lodctr" thang... try: import perfmon path, fname = os.path.split(iniName) oldPath = os.getcwd() if path: os.chdir(path) try: perfmon.LoadPerfCounterTextStrings("python.exe " + fname) finally: os.chdir(oldPath) except win32api.error as details: print("The service was installed OK, but the performance monitor") print("data could not be loaded.", details)
def GetSubList(self): ret = MakePathSubList(self.path) if os.path.split(self.path)[1] == "win32com": # Complete and utter hack for win32com. try: path = win32api.GetFullPathName(os.path.join(self.path, "..\\win32comext")) ret = ret + MakePathSubList(path) except win32ui.error: pass return ret
def GetPathName(self): # Result must be (string, int) where the int is a BOOL # - TRUE if the path refers to the original file for the document. # - FALSE if the path refers to a newly created temporary file. # - raise Exception(scode=E_FAIL) if no source file can be created/determined. trace("GetPathName") try: return win32api.GetFullPathName(self.module.__file__), 1 except (AttributeError, win32api.error): raise Exception(scode == E_FAIL)
def SubstituteVSSInFile(projectName, inName, outName): import win32api if win32api.GetFullPathName(inName) == win32api.GetFullPathName(outName): raise RuntimeError("The input and output filenames can not be the same") sourceSafe = GetSS() project = sourceSafe.VSSItem(projectName) # Find the last label label = None for version in project.Versions: if version.Label: break else: print("Couldnt find a label in the sourcesafe project!") return # Setup some local helpers for the conversion strings. vss_label = version.Label vss_date = time.asctime(time.localtime(int(version.Date))) now = time.asctime(time.localtime(time.time())) SubstituteInFile(inName, outName, (locals(), globals()))
def Boot( bEditor = 0 ): CMIFDIR = win32api.GetFullPathName(os.path.join(os.path.split(sys.argv[0])[0], "." )) # TEMP TEST FOLDER if bEditor: specificPath = "editor" os.environ['GRiNSApp']='GRiNSed' else: specificPath = "grins" os.environ['GRiNSApp']='GRiNS' CMIFPATH = [ os.path.join(CMIFDIR, '%s\\win32' % specificPath), os.path.join(CMIFDIR, 'common\\win32'), os.path.join(CMIFDIR, 'lib\\win32'), os.path.join(CMIFDIR, '%s' % specificPath), os.path.join(CMIFDIR, 'common'), os.path.join(CMIFDIR, 'lib'), os.path.join(CMIFDIR, 'pylib'), os.path.join(CMIFDIR, 'pylib\\audio'), os.path.join(CMIFDIR, 'win32\\src\\Build'), ] CMIF_USE_WIN32="ON" #CHANNELDEBUG="ON" sys.path[0:0] = CMIFPATH os.environ["CMIF"] = CMIFDIR #os.environ["CHANNELDEBUG"] = "ON" os.environ["CMIF_USE_WIN32"] = "ON" # Locate the GRiNSRes.dll file. This is presumably in the same directory as # the extensionmodules, or if frozen, in the main directory # This call allows Pythonwin to automatically find resources in it. import win32ui dllPath = os.path.split(win32ui.__file__)[0] win32ui.GetWin32Sdk().SetCurrentDirectory(dllPath) try: global resdll resdll = win32ui.LoadLibrary(os.path.join(dllPath, "GRiNSRes.dll")) resdll.AttachToMFC() except win32ui.error: win32ui.MessageBox("The application resource DLL 'GRiNSRes.dll' can not be located\r\n\r\nPlease correct this problem, and restart the application") # For now just continue!?!?! # set app registry root to GRiNS from version import registrykey, registryname win32ui.SetAppName(registryname) win32ui.SetRegistryKey(registrykey) # run the given cmif file if bEditor: import cmifed else: import grins
def TestExplorer(iexplore): if not iexplore.Visible: iexplore.Visible = -1 iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) win32api.Sleep(1000) TestObjectFromWindow() win32api.Sleep(3000) try: iexplore.Quit() except (AttributeError, pythoncom.com_error): # User got sick of waiting :) pass
def abspath(path): """Return the absolute version of a path""" try: import win32api try: path = win32api.GetFullPathName(path) except win32api.error: pass # Bad path - return unchanged. except ImportError: if not isabs(path): path = join(os.getcwd(), path) return normpath(path)
def TestExplorerEvents(): iexplore = win32com.client.DispatchWithEvents( "InternetExplorer.Application", ExplorerEvents) thread = win32api.GetCurrentThreadId() print 'TestExplorerEvents created IE object on thread %d' % thread iexplore.Visible = 1 try: iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) except pythoncom.com_error, details: print "Warning - could not open the test HTML file", details
def TestExplorer(iexplore): if not iexplore.Visible: iexplore.Visible = -1 filename = os.path.join(os.path.dirname(__file__), "..\\readme.html") iexplore.Navigate(win32api.GetFullPathName(filename)) win32api.Sleep(1000) TestObjectFromWindow() win32api.Sleep(3000) try: iexplore.Quit() except (AttributeError, pythoncom.com_error): # User got sick of waiting :) pass
def SetupEnvironment(): # Avoid pulling in win32con for just these... HKEY_LOCAL_MACHINE = -2147483646 KEY_QUERY_VALUE = 0x1 # Open the root key once, as this is quite slow on NT. try: keyName = "SOFTWARE\\Python\\PythonCore\\%s\\PythonPath\\win32com" % sys.winver key = win32api.RegOpenKey(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE) except (win32api.error, AttributeError): key = None try: found = 0 if key is not None: try: __path__.append(win32api.RegQueryValue(key, "Extensions")) found = 1 except win32api.error: # Nothing registered pass if not found: try: __path__.append( win32api.GetFullPathName(__path__[0] + "\\..\\win32comext")) except win32api.error: # Give up in disgust! pass # For the sake of developers, we also look up a "BuildPath" key # If extension modules add support, we can load their .pyd's from a completely # different directory (see the comments below) try: if key is not None: global __build_path__ __build_path__ = win32api.RegQueryValue(key, "BuildPath") __path__.append(__build_path__) except win32api.error: # __build_path__ neednt be defined. pass global __gen_path__ if key is not None: try: __gen_path__ = win32api.RegQueryValue(key, "GenPath") except win32api.error: pass finally: if key is not None: key.Close()
def GuessCMIFRoot(): selfDir = win32api.GetFullPathName( os.path.join(os.path.split(sys.argv[0])[0], ".")) l = selfDir.split('\\') dir = '' for s in l: dir = dir + s for sub in ('editor', 'grins', 'common', 'lib'): if not os.path.exists(os.path.join(dir, sub)): break else: return dir dir = dir + '\\' return r'D:\ufs\mm\cmif' # default, in case we can't find the directory dynamically
def ProcessArgs(self, args, dde=None): # If we are going to talk to a remote app via DDE, then # activate it! if dde is not None: dde.Exec("self.Activate()") if len(args) and args[0] in ['/nodde', '/new']: del args[0] # already handled. if len(args) < 1 or not args[0]: # argv[0]=='' when started without args, just like Python.exe! return try: if args[0] and args[0][0] != '/': argStart = 0 argType = win32ui.GetProfileVal("Python", "Default Arg Type", "/edit").lower() else: argStart = 1 argType = args[0] if argStart >= len(args): raise TypeError("The command line requires an additional arg.") if argType == "/edit": # Load up the default application. if dde: fname = win32api.GetFullPathName(args[argStart]) dde.Exec("win32ui.GetApp().OpenDocumentFile(%s)" % (repr(fname))) else: win32ui.GetApp().OpenDocumentFile(args[argStart]) elif argType == "/rundlg": if dde: dde.Exec("from pywin.framework import scriptutils;scriptutils.RunScript('%s', '%s', 1)" % ( args[argStart], ' '.join(args[argStart + 1:]))) else: from . import scriptutils scriptutils.RunScript(args[argStart], ' '.join(args[argStart + 1:])) elif argType == "/run": if dde: dde.Exec("from pywin.framework import scriptutils;scriptutils.RunScript('%s', '%s', 0)" % ( args[argStart], ' '.join(args[argStart + 1:]))) else: from . import scriptutils scriptutils.RunScript(args[argStart], ' '.join(args[argStart + 1:]), 0) elif argType == "/app": raise RuntimeError("/app only supported for new instances of Pythonwin.exe") elif argType == '/dde': # Send arbitary command if dde is not None: dde.Exec(args[argStart]) else: win32ui.MessageBox("The /dde command can only be used\r\nwhen Pythonwin is already running") else: raise TypeError("Command line arguments not recognised") except: # too early for print anything. win32ui.DisplayTraceback(sys.exc_info(), " - error processing command line args")
def BrandProject(vssProjectName, descFile, stampPath, filesToSubstitute, buildDesc = None, auto=0, bRebrand = 0): # vssProjectName -- The name of the VSS project to brand. # descFile -- A test file containing descriptions of the files in the release. # stampPath -- The full path to where the files referenced in descFile can be found. path=win32api.GetFullPathName(stampPath) build = vssutil.MakeNewBuildNo(vssProjectName, buildDesc, auto, bRebrand) if build is None: print("Cancelled") return bulkstamp.scan( build, stampPath, descFile ) for infile, outfile in filesToSubstitute: SubstituteVSSInFile(vssProjectName, infile, outfile) return 1
def parse_dsp(dsp): # print "Processing", dsp # For now, only support ret = [] dsp_path, dsp_name = os.path.split(dsp) try: lines = open(dsp, "r").readlines() except IOError as msg: sys.stderr.write("%s: %s\n" % (dsp, msg)) return None for line in lines: fields = line.strip().split("=", 2) if fields[0]=="SOURCE": if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']: ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) ) return ret
def __init__(self, module): self.module = module if hasattr(module, '__file__'): fname = self.module.__file__ # Check for .pyc or .pyo or even .pys! if fname[-1] in ['O', 'o', 'C', 'c', 'S', 's']: fname = fname[:-1] try: fname = win32api.GetFullPathName(fname) except win32api.error: pass else: if module.__name__ == '__main__' and len(sys.argv) > 0: fname = sys.argv[0] else: fname = "<Unknown!>" SourceCodeContainer.__init__(self, None, fname)
def GetServiceClassString(cls, argv = None): if argv is None: argv = sys.argv import pickle modName = pickle.whichmodule(cls, cls.__name__) if modName == '__main__': try: fname = win32api.GetFullPathName(argv[0]) path = os.path.split(fname)[0] # Eaaaahhhh - sometimes this will be a short filename, which causes # problems with 1.5.1 and the silly filename case rule. # Get the long name fname = os.path.join(path, win32api.FindFiles(fname)[0][8]) except win32api.error: raise error("Could not resolve the path name '%s' to a full path" % (argv[0])) modName = os.path.splitext(fname)[0] return modName + "." + cls.__name__
def __init__(self, module): self.module = module if hasattr(module, "__file__"): fname = self.module.__file__ # Check for .pyc or .pyo or even .pys! if fname[-1] in ["O", "o", "C", "c", "S", "s"]: fname = fname[:-1] try: fname = win32api.GetFullPathName(fname) except win32api.error: pass else: if module.__name__ == "__main__" and len(sys.argv) > 0: fname = sys.argv[0] else: fname = "<Unknown!>" SourceCodeContainer.__init__(self, None, fname)
def GetName(self, dnt): name = self.module.__name__ try: fname = win32api.GetFullPathName(self.module.__file__) except win32api.error: fname = self.module.__file__ except AttributeError: fname = name if dnt == axdebug.DOCUMENTNAMETYPE_APPNODE: return name.split(".")[-1] elif dnt == axdebug.DOCUMENTNAMETYPE_TITLE: return fname elif dnt == axdebug.DOCUMENTNAMETYPE_FILE_TAIL: return os.path.split(fname)[1] elif dnt == axdebug.DOCUMENTNAMETYPE_URL: return "file:%s" % fname else: raise Exception(scode=winerror.E_UNEXPECTED)
def GetServiceClassString(cls, argv = None): if argv is None: argv = sys.argv import pickle modName = pickle.whichmodule(cls, cls.__name__) if modName == '__main__': try: fname = win32api.GetFullPathName(argv[0]) path = os.path.split(fname)[0] # Eaaaahhhh - sometimes this will be a short filename, which causes # problems with 1.5.1 and the silly filename case rule. filelist = win32api.FindFiles(fname) # win32api.FindFiles will not detect files in a zip or exe. If list is empty, # skip the test and hope the file really exists. if len(filelist) != 0: # Get the long name fname = os.path.join(path, filelist[0][8]) except win32api.error: raise error("Could not resolve the path name '%s' to a full path" % (argv[0])) modName = os.path.splitext(fname)[0] return modName + "." + cls.__name__
def abspath(path): """Return the absolute version of a path""" try: import win32api except ImportError: global abspath def _abspath(path): if not isabs(path): path = join(os.getcwd(), path) return normpath(path) abspath = _abspath return _abspath(path) if path: # Empty path must return current working directory. try: path = win32api.GetFullPathName(path) except win32api.error: pass # Bad path - return unchanged. else: path = os.getcwd() return normpath(path)
def GetGoodFileName(fname): if fname[0] != "<": return win32api.GetFullPathName(fname) return fname