Exemple #1
0
def ImportFile():
    """This code looks for the current window, and determines if it can be imported.  If not,
    it will prompt for a file name, and allow it to be imported."""
    try:
        pathName = GetActiveFileName()
    except KeyboardInterrupt:
        pathName = None

    if pathName is not None:
        if os.path.splitext(pathName)[1].lower() not in (".py", ".pyw",
                                                         ".pyx"):
            pathName = None

    if pathName is None:
        openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
        dlg = win32ui.CreateFileDialog(
            1, None, None, openFlags,
            "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||")
        dlg.SetOFNTitle("Import Script")
        if dlg.DoModal() != win32con.IDOK:
            return 0

        pathName = dlg.GetPathName()

    # If already imported, dont look for package
    path, modName = os.path.split(pathName)
    modName, modExt = os.path.splitext(modName)
    newPath = None
    # note that some packages (*cough* email *cough*) use "lazy importers"
    # meaning sys.modules can change as a side-effect of looking at
    # module.__file__ - so we must take a copy (ie, items() in py2k,
    # list(items()) in py3k)
    for key, mod in list(sys.modules.items()):
        if getattr(mod, "__file__", None):
            fname = mod.__file__
            base, ext = os.path.splitext(fname)
            if ext.lower() in [".pyo", ".pyc"]:
                ext = ".py"
            fname = base + ext
            if win32ui.ComparePath(fname, pathName):
                modName = key
                break
    else:  # for not broken
        modName, newPath = GetPackageModuleName(pathName)
        if newPath:
            sys.path.append(newPath)

    if modName in sys.modules:
        bNeedReload = 1
        what = "reload"
    else:
        what = "import"
        bNeedReload = 0

    win32ui.SetStatusText(what.capitalize() + "ing module...", 1)
    win32ui.DoWaitCursor(1)
    # 	win32ui.GetMainFrame().BeginWaitCursor()

    try:
        # always do an import, as it is cheap if it's already loaded.  This ensures
        # it is in our name space.
        codeObj = compile("import " + modName, "<auto import>", "exec")
    except SyntaxError:
        win32ui.SetStatusText('Invalid filename for import: "' + modName + '"')
        return
    try:
        exec(codeObj, __main__.__dict__)
        mod = sys.modules.get(modName)
        if bNeedReload:
            from importlib import reload

            mod = reload(sys.modules[modName])
        win32ui.SetStatusText("Successfully " + what + "ed module '" +
                              modName + "': %s" %
                              getattr(mod, "__file__", "<unkown file>"))
    except:
        _HandlePythonFailure(what)
    win32ui.DoWaitCursor(0)
Exemple #2
0
def ImportFile():
	""" This code looks for the current window, and determines if it can be imported.  If not,
	it will prompt for a file name, and allow it to be imported. """
	try:
		pathName = GetActiveFileName()
	except KeyboardInterrupt:
		pathName = None

	if pathName is not None:
		if string.lower(os.path.splitext(pathName)[1]) <> ".py":
			pathName = None

	if pathName is None:
		openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_FILEMUSTEXIST
		dlg = win32ui.CreateFileDialog(1,None,None,openFlags, "Python Scripts (*.py)|*.py||")
		dlg.SetOFNTitle("Import Script")
		if dlg.DoModal()!=win32con.IDOK:
			return 0

		pathName = dlg.GetPathName()
		
	# If already imported, dont look for package
	path, modName = os.path.split(pathName)
	modName, modExt = os.path.splitext(modName)
	newPath = None
	for key, mod in sys.modules.items():
		if hasattr(mod, '__file__'):
			fname = mod.__file__
			base, ext = os.path.splitext(fname)
			if string.lower(ext) in ['.pyo', '.pyc']:
				ext = '.py'
			fname = base + ext
			if win32ui.ComparePath(fname, pathName):
				modName = key
				break
	else: # for not broken
		modName, newPath = GetPackageModuleName(pathName)
		if newPath: sys.path.append(newPath)

	if sys.modules.has_key(modName):
		bNeedReload = 1
		what = "reload"
	else:
		what = "import"
		bNeedReload = 0
	
	win32ui.SetStatusText(string.capitalize(what)+'ing module...',1)
	win32ui.DoWaitCursor(1)
#	win32ui.GetMainFrame().BeginWaitCursor()

	try:
		# always do an import, as it is cheap is already loaded.  This ensures
		# it is in our name space.
		codeObj = compile('import '+modName,'<auto import>','exec')
	except SyntaxError:
		win32ui.SetStatusText('Invalid filename for import: "' +modName+'"')
		return
	try:
		exec codeObj in __main__.__dict__
		if bNeedReload:
			reload(sys.modules[modName])
#			codeObj = compile('reload('+modName+')','<auto import>','eval')
#			exec codeObj in __main__.__dict__
		win32ui.SetStatusText('Successfully ' + what + "ed module '"+modName+"'")
	except:
		_HandlePythonFailure(what)
	win32ui.DoWaitCursor(0)
Exemple #3
0
def ImportFile():
	""" This code looks for the current window, and determines if it can be imported.  If not,
	it will prompt for a file name, and allow it to be imported. """
	try:
		pathName = GetActiveFileName()
	except KeyboardInterrupt:
		pathName = None

	if pathName is not None:
		if os.path.splitext(pathName)[1].lower() not in ('.py','.pyw','.pyx'):
			pathName = None

	if pathName is None:
		openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_FILEMUSTEXIST
		dlg = win32ui.CreateFileDialog(1,None,None,openFlags, "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||")
		dlg.SetOFNTitle("Import Script")
		if dlg.DoModal()!=win32con.IDOK:
			return 0

		pathName = dlg.GetPathName()
		
	# If already imported, dont look for package
	path, modName = os.path.split(pathName)
	modName, modExt = os.path.splitext(modName)
	newPath = None
	# note that some packages (*cough* email *cough*) use "lazy importers"
	# meaning sys.modules can change as a side-effect of looking at
	# module.__file__ - so we must take a copy (ie, items() in py2k,
	# list(items()) in py3k)
	for key, mod in sys.modules.items():
		if hasattr(mod, '__file__'):
			fname = mod.__file__
			base, ext = os.path.splitext(fname)
			if ext.lower() in ['.pyo', '.pyc']:
				ext = '.py'
			fname = base + ext
			if win32ui.ComparePath(fname, pathName):
				modName = key
				break
	else: # for not broken
		modName, newPath = GetPackageModuleName(pathName)
		if newPath: sys.path.append(newPath)

	if modName in sys.modules:
		bNeedReload = 1
		what = "reload"
	else:
		what = "import"
		bNeedReload = 0
	
	win32ui.SetStatusText(what.capitalize()+'ing module...',1)
	win32ui.DoWaitCursor(1)
#	win32ui.GetMainFrame().BeginWaitCursor()

	try:
		# always do an import, as it is cheap if it's already loaded.  This ensures
		# it is in our name space.
		codeObj = compile('import '+modName,'<auto import>','exec')
	except SyntaxError:
		win32ui.SetStatusText('Invalid filename for import: "' +modName+'"')
		return
	try:
		exec codeObj in __main__.__dict__
		mod = sys.modules.get(modName)
		if bNeedReload:
			try:
				## The interpreter sees this import as a local assignment, so Python 2.x throws
				##	UnboundLocalError: local variable 'reload' referenced before assignment
				## when you try to use reload after this fails
				from imp import reload as my_reload # py3k
			except ImportError:
				my_reload = reload # reload a builtin in py2k
			mod = my_reload(sys.modules[modName])
		win32ui.SetStatusText('Successfully ' + what + "ed module '"+modName+"': %s" % getattr(mod,'__file__',"<unkown file>"))
	except:
		_HandlePythonFailure(what)
	win32ui.DoWaitCursor(0)