Ejemplo n.º 1
0
def demo():
    try:
        # seeif I can locate the demo files.
        import fontdemo
    except ImportError:
        # else put the demos direectory on the path (if not already)
        try:
            instPath = regutil.GetRegistryDefaultValue(
                regutil.BuildDefaultPythonKey() + "\\InstallPath"
            )
        except win32api.error:
            print(
                "The InstallPath can not be located, and the Demos directory is not on the path"
            )
            instPath = "."

        demosDir = win32ui.FullPath(instPath + "\\Demos")
        for path in sys.path:
            if win32ui.FullPath(path) == demosDir:
                break
        else:
            sys.path.append(demosDir)
        import fontdemo

    import sys

    if "/go" in sys.argv:
        for name, cmd in demos:
            try:
                exec(cmd)
            except:
                print(
                    "Demo of %s failed - %s:%s"
                    % (cmd, sys.exc_info()[0], sys.exc_info()[1])
                )
        return
    # Otherwise allow the user to select the demo to run

    import pywin.dialogs.list

    while 1:
        rc = pywin.dialogs.list.SelectFromLists("Select a Demo", demos, ["Demo Title"])
        if rc is None:
            break
        title, cmd = demos[rc]
        try:
            exec(cmd)
        except:
            print(
                "Demo of %s failed - %s:%s"
                % (title, sys.exc_info()[0], sys.exc_info()[1])
            )
Ejemplo n.º 2
0
	def SetApplicationPaths(self):
		# Load the users/application paths
		new_path = []
		apppath=win32ui.GetProfileVal('Python','Application Path','').split(';')
		for path in apppath:
			if len(path)>0:
				new_path.append(win32ui.FullPath(path))
		for extra_num in range(1,11):
			apppath=win32ui.GetProfileVal('Python','Application Path %d'%extra_num,'').split(';')
			if len(apppath) == 0:
				break
			for path in apppath:
				if len(path)>0:
					new_path.append(win32ui.FullPath(path))
		sys.path = new_path + sys.path
Ejemplo n.º 3
0
def GetPackageModuleName(fileName):
	"""Given a filename, return (module name, new path).
	   eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path.
	   If no package found, will return ("my", "c:\a\b\c")
	"""
	path, fname = os.path.split(fileName)
	path=origPath=win32ui.FullPath(path)
	fname = os.path.splitext(fname)[0]
	modBits = []
	newPathReturn = None
	if not IsOnPythonPath(path):
		# Module not directly on the search path - see if under a package.
		while len(path)>3: # ie 'C:\'
			path, modBit = os.path.split(path)
			modBits.append(modBit)
			# If on path, _and_ existing package of that name loaded.
			if IsOnPythonPath(path) and sys.modules.has_key(modBit) and \
			   ( os.path.exists(os.path.join(path, '__init__.py')) or \
			     os.path.exists(os.path.join(path, '__init__.pyc')) or \
			     os.path.exists(os.path.join(path, '__init__.pyo')) \
			   ):
				modBits.reverse()
				return string.join(modBits, ".") + "." + fname, newPathReturn
			# Not found - look a level higher
		else:
			newPathReturn = origPath
		
	return fname, newPathReturn
Ejemplo n.º 4
0
def LocatePythonFile( fileName, bBrowseIfDir = 1 ):
	" Given a file name, return a fully qualified file name, or None "
	# first look for the exact file as specified
	if not os.path.isfile(fileName):
		# Go looking!
		baseName = fileName
		for path in sys.path:
			fileName = os.path.join(path, baseName)
			if os.path.isdir(fileName):
				if bBrowseIfDir:
					d=win32ui.CreateFileDialog(1, "*.py", None, 0, "Python Files (*.py)|*.py|All files|*.*")
					d.SetOFNInitialDir(fileName)
					rc=d.DoModal()
					if rc==win32con.IDOK:
						fileName = d.GetPathName()
						break
					else:
						return None
			else:
				fileName = fileName + ".py"
				if os.path.isfile(fileName):
					break # Found it!

		else:	# for not broken out of
			return None
	return win32ui.FullPath(fileName)
Ejemplo n.º 5
0
def FixArgFileName(fileName):
    """Convert a filename on the commandline to something useful.
    Given an automatic filename on the commandline, turn it a python module name,
    with the path added to sys.path. """
    import os
    path, fname = os.path.split(fileName)
    if len(path) > 0:
        path = win32ui.FullPath(path)
    else:
        path = win32ui.FullPath(os.curdir)
    # must check that the command line arg's path is in sys.path
    for syspath in sys.path:
        if win32ui.FullPath(syspath) == path:
            break
    else:
        sys.path.append(path)
    return os.path.splitext(fname)[0]
Ejemplo n.º 6
0
def IsOnPythonPath(path):
	"Given a path only, see if it is on the Pythonpath.  Assumes path is a full path spec."
	# must check that the command line arg's path is in sys.path
	for syspath in sys.path:
		try:
			# Python 1.5 and later allows an empty sys.path entry.
			if syspath and win32ui.FullPath(syspath)==path:
				return 1
		except win32ui.error, details:
			print "Warning: The sys.path entry '%s' is invalid\n%s" % (syspath, details)
Ejemplo n.º 7
0
def RunScript(defName=None, defArgs=None, bShowDialog = 1, debuggingType=None):
	global lastScript, lastArgs, lastDebuggingType
	_debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me!

	# Get the debugger - may be None!
	debugger = GetDebugger()

	if defName is None:
		try:
			pathName = GetActiveFileName()
		except KeyboardInterrupt:
			return # User cancelled save.
	else:
		pathName = defName
	if not pathName:
		pathName = lastScript
	if defArgs is None:
		args = ''
		if pathName==lastScript:
			args = lastArgs
	else:
		args = defArgs
	if debuggingType is None: debuggingType = lastDebuggingType

	if not pathName or bShowDialog:
		dlg = DlgRunScript(debugger is not None)
		dlg['script'] = pathName
		dlg['args'] = args
		dlg['debuggingType'] = debuggingType
		if dlg.DoModal() != win32con.IDOK:
			return
		script=dlg['script']
		args=dlg['args']
		debuggingType = dlg['debuggingType']
		if not script: return
		if debuggingType == RS_DEBUGGER_GO and debugger is not None:
			# This may surprise users - they select "Run under debugger", but
			# it appears not to!  Only warn when they pick from the dialog!
			# First - ensure the debugger is activated to pickup any break-points
			# set in the editor.
			try:
				# Create the debugger, but _dont_ init the debugger GUI.
				rd = debugger._GetCurrentDebugger()
			except AttributeError:
				rd = None
			if rd is not None and len(rd.breaks)==0:
				msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?"
				rc = win32ui.MessageBox(msg, win32ui.LoadString(win32ui.IDR_DEBUGGER), win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION)
				if rc == win32con.IDCANCEL:
					return
				if rc == win32con.IDYES:
					debuggingType = RS_DEBUGGER_STEP

		lastDebuggingType = debuggingType
		lastScript = script
		lastArgs = args
	else:
		script = pathName

	# try and open the script.
	if len(os.path.splitext(script)[1])==0:	# check if no extension supplied, and give one.
			script = script + '.py'
	# If no path specified, try and locate the file
	path, fnameonly = os.path.split(script)
	if len(path)==0:
		try:
			os.stat(fnameonly) # See if it is OK as is...
			script = fnameonly
		except os.error:
			fullScript = app.LocatePythonFile(script)
			if fullScript is None:
				win32ui.MessageBox("The file '%s' can not be located" % script )
				return
			script = fullScript
	else:
		path = win32ui.FullPath(path)
		if not IsOnPythonPath(path): sys.path.append(path)

	try:
		f = open(script)
	except IOError, (code, msg):
		win32ui.MessageBox("The file could not be opened - %s (%d)" % (msg, code))
		return
Ejemplo n.º 8
0
def RunScript(defName=None, defArgs=None, bShowDialog = 1, bUnderDebugger=None, bPostMortemDebugger = None):
    global lastScript, lastArgs, lastbUnderDebugger, lastbPostMortemDebugger

    # Get the debugger - may be None!
    debugger = GetDebugger()

    if defName is None:
        try:
            pathName = GetActiveFileName()
        except KeyboardInterrupt:
            return
    else:
        pathName = defName
    if defArgs is None:
        args = ''
        if pathName is None or len(pathName)==0:
            pathName = lastScript
        if pathName==lastScript:
            args = lastArgs
    else:
        args = defArgs
    if bUnderDebugger is None: bUnderDebugger = debugger is not None and lastbUnderDebugger
    if bPostMortemDebugger is None: bPostMortemDebugger = debugger is not None and lastbPostMortemDebugger

    if not pathName or bShowDialog:
        dlg = DlgRunScript()
        dlg['script'] = pathName
        dlg['args'] = args
        dlg['bUnderDebugger'] = bUnderDebugger
        dlg['bPostMortemDebugger'] = bPostMortemDebugger
        if dlg.DoModal() != win32con.IDOK:
            return
        script=dlg['script']
        args=dlg['args']
        bUnderDebugger = dlg['bUnderDebugger']
        bPostMortemDebugger = dlg['bPostMortemDebugger']
        if not script: return # User cancelled.
    else:
        script = pathName
    lastScript = script
    lastArgs = args
    lastbUnderDebugger = bUnderDebugger
    lastbPostMortemDebugger = bPostMortemDebugger
    # try and open the script.
    if len(os.path.splitext(script)[1])==0: # check if no extension supplied, and give one.
        script = script + '.py'
    # If no path specified, try and locate the file
    path, fnameonly = os.path.split(script)
    if len(path)==0:
        try:
            os.stat(fnameonly) # See if it is OK as is...
            script = fnameonly
        except os.error:
            fullScript = app.LocatePythonFile(script)
            if fullScript is None:
                win32ui.MessageBox("The file '%s' can not be located" % script )
                return
            script = fullScript
    else:
        path = win32ui.FullPath(path)
        if not IsOnPythonPath(path): sys.path.append(path)

    try:
        f = open(script)
    except IOError, (code, msg):
        win32ui.MessageBox("The file could not be opened - %s (%d)" % (msg, code))
        return
Ejemplo n.º 9
0
def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
    global lastScript, lastArgs, lastDebuggingType
    _debugger_stop_frame_ = 1  # Magic variable so the debugger will hide me!

    # Get the debugger - may be None!
    debugger = GetDebugger()

    if defName is None:
        try:
            pathName = GetActiveFileName()
        except KeyboardInterrupt:
            return  # User cancelled save.
    else:
        pathName = defName
    if not pathName:
        pathName = lastScript
    if defArgs is None:
        args = ""
        if pathName == lastScript:
            args = lastArgs
    else:
        args = defArgs
    if debuggingType is None:
        debuggingType = lastDebuggingType

    if not pathName or bShowDialog:
        dlg = DlgRunScript(debugger is not None)
        dlg["script"] = pathName
        dlg["args"] = args
        dlg["debuggingType"] = debuggingType
        if dlg.DoModal() != win32con.IDOK:
            return
        script = dlg["script"]
        args = dlg["args"]
        debuggingType = dlg["debuggingType"]
        if not script:
            return
        if debuggingType == RS_DEBUGGER_GO and debugger is not None:
            # This may surprise users - they select "Run under debugger", but
            # it appears not to!  Only warn when they pick from the dialog!
            # First - ensure the debugger is activated to pickup any break-points
            # set in the editor.
            try:
                # Create the debugger, but _dont_ init the debugger GUI.
                rd = debugger._GetCurrentDebugger()
            except AttributeError:
                rd = None
            if rd is not None and len(rd.breaks) == 0:
                msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?"
                rc = win32ui.MessageBox(
                    msg,
                    win32ui.LoadString(win32ui.IDR_DEBUGGER),
                    win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION,
                )
                if rc == win32con.IDCANCEL:
                    return
                if rc == win32con.IDYES:
                    debuggingType = RS_DEBUGGER_STEP

        lastDebuggingType = debuggingType
        lastScript = script
        lastArgs = args
    else:
        script = pathName

    # try and open the script.
    if (len(os.path.splitext(script)[1]) == 0
        ):  # check if no extension supplied, and give one.
        script = script + ".py"
    # If no path specified, try and locate the file
    path, fnameonly = os.path.split(script)
    if len(path) == 0:
        try:
            os.stat(fnameonly)  # See if it is OK as is...
            script = fnameonly
        except os.error:
            fullScript = LocatePythonFile(script)
            if fullScript is None:
                win32ui.MessageBox("The file '%s' can not be located" % script)
                return
            script = fullScript
    else:
        path = win32ui.FullPath(path)
        if not IsOnPythonPath(path):
            sys.path.append(path)

    # py3k fun: If we use text mode to open the file, we get \r\n
    # translated so Python allows the syntax (good!), but we get back
    # text already decoded from the default encoding (bad!) and Python
    # ignores any encoding decls (bad!).  If we use binary mode we get
    # the raw bytes and Python looks at the encoding (good!) but \r\n
    # chars stay in place so Python throws a syntax error (bad!).
    # So: so the binary thing and manually normalize \r\n.
    try:
        f = open(script, "rb")
    except IOError as exc:
        win32ui.MessageBox("The file could not be opened - %s (%d)" %
                           (exc.strerror, exc.errno))
        return

    # Get the source-code - as above, normalize \r\n
    code = f.read().replace(byte_crlf, byte_lf).replace(byte_cr,
                                                        byte_lf) + byte_lf

    # Remember and hack sys.argv for the script.
    oldArgv = sys.argv
    sys.argv = ParseArgs(args)
    sys.argv.insert(0, script)
    # sys.path[0] is the path of the script
    oldPath0 = sys.path[0]
    newPath0 = os.path.split(script)[0]
    if not oldPath0:  # if sys.path[0] is empty
        sys.path[0] = newPath0
        insertedPath0 = 0
    else:
        sys.path.insert(0, newPath0)
        insertedPath0 = 1
    bWorked = 0
    win32ui.DoWaitCursor(1)
    base = os.path.split(script)[1]
    # Allow windows to repaint before starting.
    win32ui.PumpWaitingMessages()
    win32ui.SetStatusText("Running script %s..." % base, 1)
    exitCode = 0
    from pywin.framework import interact

    # Check the debugger flags
    if debugger is None and (debuggingType != RS_DEBUGGER_NONE):
        win32ui.MessageBox(
            "No debugger is installed.  Debugging options have been ignored!")
        debuggingType = RS_DEBUGGER_NONE

    # Get a code object - ignore the debugger for this, as it is probably a syntax error
    # at this point
    try:
        codeObject = compile(code, script, "exec")
    except:
        # Almost certainly a syntax error!
        _HandlePythonFailure("run script", script)
        # No code object which to run/debug.
        return
    __main__.__file__ = script
    try:
        if debuggingType == RS_DEBUGGER_STEP:
            debugger.run(codeObject, __main__.__dict__, start_stepping=1)
        elif debuggingType == RS_DEBUGGER_GO:
            debugger.run(codeObject, __main__.__dict__, start_stepping=0)
        else:
            # Post mortem or no debugging
            exec(codeObject, __main__.__dict__)
        bWorked = 1
    except bdb.BdbQuit:
        # Dont print tracebacks when the debugger quit, but do print a message.
        print("Debugging session cancelled.")
        exitCode = 1
        bWorked = 1
    except SystemExit as code:
        exitCode = code
        bWorked = 1
    except KeyboardInterrupt:
        # Consider this successful, as we dont want the debugger.
        # (but we do want a traceback!)
        if interact.edit and interact.edit.currentView:
            interact.edit.currentView.EnsureNoPrompt()
        traceback.print_exc()
        if interact.edit and interact.edit.currentView:
            interact.edit.currentView.AppendToPrompt([])
        bWorked = 1
    except:
        if interact.edit and interact.edit.currentView:
            interact.edit.currentView.EnsureNoPrompt()
        traceback.print_exc()
        if interact.edit and interact.edit.currentView:
            interact.edit.currentView.AppendToPrompt([])
        if debuggingType == RS_DEBUGGER_PM:
            debugger.pm()
    del __main__.__file__
    sys.argv = oldArgv
    if insertedPath0:
        del sys.path[0]
    else:
        sys.path[0] = oldPath0
    f.close()
    if bWorked:
        win32ui.SetStatusText("Script '%s' returned exit code %s" %
                              (script, exitCode))
    else:
        win32ui.SetStatusText("Exception raised while running script  %s" %
                              base)
    try:
        sys.stdout.flush()
    except AttributeError:
        pass

    win32ui.DoWaitCursor(0)
Ejemplo n.º 10
0
# import win32traceutil # Just uncomment this line to see error output!

# An old class I used to use - generally only useful if Pythonwin is running under MSVC
#class DebugOutput:
#	softspace=1
#	def write(self,message):
#		win32ui.OutputDebug(message)
#sys.stderr=sys.stdout=DebugOutput()

# To fix a problem with Pythonwin when started from the Pythonwin directory,
# we update the pywin path to ensure it is absolute.
# If it is indeed relative, it will be relative to our current directory.
# If its already absolute, then this will have no affect.
import pywin, pywin.framework

pywin.__path__[0] = win32ui.FullPath(pywin.__path__[0])
pywin.framework.__path__[0] = win32ui.FullPath(pywin.framework.__path__[0])

# make a few wierd sys values.  This is so later we can clobber sys.argv to trick
# scripts when running under a GUI environment.

moduleName = "pywin.framework.intpyapp"
sys.appargvoffset = 0
sys.appargv = sys.argv[:]
# Must check for /app param here.
if len(sys.argv) >= 2 and sys.argv[0].lower() == '/app':
    from . import cmdline
    moduleName = cmdline.FixArgFileName(sys.argv[1])
    sys.appargvoffset = 2
    newargv = sys.argv[sys.appargvoffset:]
    #	newargv.insert(0, sys.argv[0])