예제 #1
0
파일: packages.py 프로젝트: ver007/NovalIDE
 def UninstallPackage(self, interpreter):
     should_root = False
     if not sysutils.isWindows():
         should_root = not interpreter.IsPythonlibWritable()
     package_name = self.value_ctrl.GetValue().strip()
     if os.path.basename(package_name) == "requirements.txt":
         if not sysutils.isWindows() and should_root:
             command = "pkexec " + strutils.emphasis_path(
                 interpreter.GetPipPath()) + " uninstall -y -r %s" % (
                     package_name)
         else:
             command = strutils.emphasis_path(interpreter.GetPipPath(
             )) + " uninstall -y -r %s" % (package_name)
     else:
         if not sysutils.isWindows() and should_root:
             command = "pkexec " + strutils.emphasis_path(
                 interpreter.GetPipPath()) + " uninstall -y %s" % (
                     package_name)
         else:
             command = strutils.emphasis_path(interpreter.GetPipPath(
             )) + " uninstall -y %s" % (package_name)
     self.output_ctrl.write(command + os.linesep)
     self.call_back = self.output_ctrl.write
     t = threading.Thread(target=self.ExecCommandAndOutput,
                          args=(command, self))
     t.start()
예제 #2
0
 def LoadDefaultInterpreter(self):
     if self.LoadPythonInterpretersFromConfig():
         self.SetCurrentInterpreter(self.DefaultInterpreter)
         return
     self.LoadPythonInterpreters()
     if 0 == len(self.interpreters):
         if sysutils.isWindows():
             dlg = wx.MessageDialog(None, _("No python interpreter found in your computer,will use the builtin interpreter instead"), \
                 _("Python interpreter not found"), wx.OK | wx.ICON_WARNING)
         else:
             dlg = wx.MessageDialog(None,
                                    _("Python interpreter not found!"),
                                    _("No Interpreter"),
                                    wx.OK | wx.ICON_WARNING)
         dlg.ShowModal()
         dlg.Destroy()
     if sysutils.isWindows() and None == self.GetInterpreterByName(
             BUILTIN_INTERPRETER_NAME):
         self.LoadBuiltinInterpreter()
     if 1 == len(self.interpreters):
         self.MakeDefaultInterpreter()
     elif 1 < len(self.interpreters):
         self.ChooseDefaultInterpreter()
     self.SetCurrentInterpreter(self.DefaultInterpreter)
     self.SavePythonInterpretersConfig()
예제 #3
0
 def CreatePythonVirtualEnv(self, name, location, include_site_packages,
                            interpreter, progress_dlg):
     progress_dlg.call_back = progress_dlg.AppendMsg
     if not interpreter.Packages.has_key('virtualenv'):
         progress_dlg.msg = "install virtualenv package..."
         should_root = False
         if not sysutils.isWindows():
             should_root = not interpreter.IsPythonlibWritable(interpreter)
         if not sysutils.isWindows() and should_root:
             command = "pkexec " + strutils.emphasis_path(
                 interpreter.GetPipPath()) + " install virtualenv"
         else:
             command = strutils.emphasis_path(
                 interpreter.GetPipPath()) + " install virtualenv"
         self.ExecCommandAndOutput(command, progress_dlg)
     should_root = not self.IsLocationWritable(location)
     if not sysutils.isWindows() and should_root:
         command = "pkexec " + strutils.emphasis_path(
             self.GetVirtualEnvPath(
                 interpreter)) + " " + strutils.emphasis_path(location)
     else:
         command = strutils.emphasis_path(
             self.GetVirtualEnvPath(
                 interpreter)) + " " + strutils.emphasis_path(location)
     if include_site_packages:
         command += " --system-site-packages"
     self.ExecCommandAndOutput(command, progress_dlg)
     progress_dlg.KeepGoing = False
예제 #4
0
 def ProcessEvent(self, event):
     id = event.GetId()
     item = self.GetSelection()
     item_type, item_path = self.GetPyData(item)
     if id == OPEN_CMD_PATH_ID:
         if item_type == ResourceView.DIRECTORY_RES_TYPE:
             filePath = item_path
         else:
             filePath = os.path.dirname(item_path)
         if sysutils.isWindows():
             filePath = filePath.decode('gbk')
         err_code, msg = fileutils.open_path_in_terminator(filePath)
         if err_code != ERROR_OK:
             wx.MessageBox(msg, style=wx.OK | wx.ICON_ERROR)
     elif id == OPEN_DIR_PATH_ID:
         err_code, msg = fileutils.open_file_directory(item_path)
         if err_code != ERROR_OK:
             wx.MessageBox(msg, style=wx.OK | wx.ICON_ERROR)
     elif id == COPY_FULLPATH_ID:
         sysutils.CopyToClipboard(item_path)
     elif id == REFRESH__PATH_ID:
         self.Freeze()
         self.DeleteChildren(item)
         ResourceView(self.GetParent()).LoadDir(item, item_path)
         if self.GetChildrenCount(item) > 0:
             self.SetItemHasChildren(item, True)
         self.Thaw()
예제 #5
0
파일: download.py 프로젝트: ver007/NovalIDE
 def DownloadFileContent(self,download_file_path,req,download_progress_dlg):
     is_cancel = False
     f = open(download_file_path, "wb")
     try:
         for chunk in req.iter_content(chunk_size=512):
             if chunk:
                 if not download_progress_dlg.keep_going:
                     is_cancel = True
                     break
                 f.write(chunk)
                 download_progress_dlg._progress += len(chunk)
                 if sysutils.isWindows():
                     Publisher.sendMessage(NOVAL_MSG_UI_DOWNLOAD_PROGRESS,temp = download_progress_dlg._progress,msg="")
                 else:
                     wx.MilliSleep(50)
                     wx.SafeYield(download_progress_dlg,True)
                     wx.CallAfter(Publisher.sendMessage,NOVAL_MSG_UI_DOWNLOAD_PROGRESS,temp=download_progress_dlg._progress,msg="")
     except Exception as e:
         wx.MessageBox(_("Download fail:%s") % e,style=wx.OK|wx.ICON_ERROR)
         time.sleep(1)
         download_progress_dlg.Destroy()
         return
     f.close()
     time.sleep(1)
     download_progress_dlg.keep_going = False
     download_progress_dlg.Destroy()
     if self._call_back is not None and not is_cancel:
         wx.CallAfter(self._call_back,download_file_path)
예제 #6
0
def getAllExistingFiles(files, basepath=None, forceForwardSlashes=False):
    """For each file in files, if it exists, adds its absolute path to the rtn list. If file is a dir, calls this function recursively on all child files in the dir.
    If basepath is set, and if the file being processed is relative to basedir, adds that relative path to rtn list instead of the abs path.
    Is this is Windows, and forceForwardSlashes is True, make sure returned paths only have forward slashes."""
    if isinstance(files, basestring):
        files = [files]
    rtn = []
    for file in files:
        if os.path.exists(file):
            if os.path.isfile(file):
                if basepath and hasAncestorDir(file, basepath):
                    rtn.append(getRelativePath(file, basepath))
                else:
                    rtn.append(os.path.abspath(str(file)))
            elif os.path.isdir(file):
                dircontent = [os.path.join(file, f) for f in os.listdir(file)]
                rtn.extend(getAllExistingFiles(dircontent, basepath))

    if forceForwardSlashes and sysutils.isWindows():
        newRtn = []
        for f in rtn:
            newRtn.append(f.replace("\\", "/"))
        rtn = newRtn

    return rtn
예제 #7
0
def open_file_directory(file_path):
    """
        Opens the parent directory of a file, selecting the file if possible.
    """
    err_code = ERROR_OK
    err_msg = ''
    if sysutils.isWindows():
        # Normally we can just run `explorer /select, filename`, but Python 2
        # always calls CreateProcessA, which doesn't support Unicode. We could
        # call CreateProcessW with ctypes, but the following is more robust.
        import ctypes
        import win32api

        ctypes.windll.ole32.CoInitialize(None)
        # Not sure why this is always UTF-8.
        pidl = ctypes.windll.shell32.ILCreateFromPathW(file_path)
        if 0 == pidl:
            pidl = ctypes.windll.shell32.ILCreateFromPathA(file_path)

        if 0 == pidl:
            err_code = ctypes.windll.kernel32.GetLastError()
            err_msg = win32api.FormatMessage(err_code)
        ctypes.windll.shell32.SHOpenFolderAndSelectItems(pidl, 0, None, 0)
        ctypes.windll.shell32.ILFree(pidl)
        ctypes.windll.ole32.CoUninitialize()
    else:
        subprocess.Popen(["nautilus", file_path])
    return err_code, err_msg
예제 #8
0
    def __init__(self,
                 name,
                 executable_path,
                 id=None,
                 is_valid_interpreter=False):
        if sysutils.isWindows():
            if os.path.basename(executable_path
                                ) == PythonInterpreter.WINDOW_EXECUTABLE_NAME:
                self._window_path = executable_path
                console_path = os.path.join(
                    os.path.dirname(executable_path),
                    PythonInterpreter.CONSOLE_EXECUTABLE_NAME)
                self._console_path = console_path
                executable_path = self._console_path
            elif os.path.basename(
                    executable_path
            ) == PythonInterpreter.CONSOLE_EXECUTABLE_NAME:
                self._console_path = executable_path
                window_path = os.path.join(
                    os.path.dirname(executable_path),
                    PythonInterpreter.WINDOW_EXECUTABLE_NAME)
                self._window_path = window_path

        super(PythonInterpreter, self).__init__(name, executable_path, id,
                                                False)
        self._is_valid_interpreter = is_valid_interpreter
        self._version = UNKNOWN_VERSION_NAME
        self._is_analysing = False
        self._is_analysed = False
        self._is_loading_package = False
        if not is_valid_interpreter:
            self.GetVersion()
        if not is_valid_interpreter and self._is_valid_interpreter:
            self.GetSysPathList()
            self.GetBuiltins()
예제 #9
0
 def SavePythonInterpretersConfig(self):
     config = wx.ConfigBase_Get()
     if sysutils.isWindows():
         dct = self.ConvertInterpretersToDictList()
         if dct == []:
             return
         config.Write(self.KEY_PREFIX, pickle.dumps(dct))
     else:
         prefix = self.KEY_PREFIX
         id_list = [str(kl.Id) for kl in self.interpreters]
         config.Write(prefix, os.pathsep.join(id_list))
         for kl in self.interpreters:
             config.WriteInt("%s/%d/Id" % (prefix, kl.Id), kl.Id)
             config.Write("%s/%d/Name" % (prefix, kl.Id), kl.Name)
             config.Write("%s/%d/Version" % (prefix, kl.Id), kl.Version)
             config.Write("%s/%d/Path" % (prefix, kl.Id), kl.Path)
             config.WriteInt("%s/%d/Default" % (prefix, kl.Id), kl.Default)
             config.Write("%s/%d/SysPathList" % (prefix, kl.Id),
                          os.pathsep.join(kl.SysPathList))
             config.Write("%s/%d/PythonPathList" % (prefix, kl.Id),
                          os.pathsep.join(kl.PythonPathList))
             config.Write("%s/%d/Builtins" % (prefix, kl.Id),
                          os.pathsep.join(kl.Builtins))
             config.Write("%s/%d/Environ" % (prefix, kl.Id),
                          json.dumps(kl.Environ.environ))
             config.Write("%s/%d/Packages" % (prefix, kl.Id),
                          json.dumps(kl.Packages))
예제 #10
0
 def LoadPythonInterpreters(self):
     if sysutils.isWindows():
         import _winreg
         ROOT_KEY_LIST = [
             _winreg.HKEY_LOCAL_MACHINE, _winreg.HKEY_CURRENT_USER
         ]
         ROOT_KEY_NAMES = ['LOCAL_MACHINE', 'CURRENT_USER']
         for k, root_key in enumerate(ROOT_KEY_LIST):
             try:
                 open_key = _winreg.OpenKey(root_key,
                                            r"SOFTWARE\Python\Pythoncore")
                 countkey = _winreg.QueryInfoKey(open_key)[0]
                 keylist = []
                 for i in range(int(countkey)):
                     name = _winreg.EnumKey(open_key, i)
                     try:
                         child_key = _winreg.OpenKey(
                             root_key,
                             r"SOFTWARE\Python\Pythoncore\%s" % name)
                         install_path = _winreg.QueryValue(
                             child_key, "InstallPath")
                         interpreter = Interpreter.PythonInterpreter(
                             name,
                             os.path.join(
                                 install_path, Interpreter.
                                 PythonInterpreter.CONSOLE_EXECUTABLE_NAME))
                         if not interpreter.IsValidInterpreter:
                             app_debugLogger.error(
                                 "interpreter name %s path %s,version %s is not a valid interpreter",
                                 interpreter.Name, interpreter.Path,
                                 interpreter.Version)
                             continue
                         self.interpreters.insert(0, interpreter)
                         app_debugLogger.info(
                             "load python interpreter from regkey success,path is %s,version is %s",
                             interpreter.Path, interpreter.Version)
                         help_key = _winreg.OpenKey(child_key, "Help")
                         help_path = _winreg.QueryValue(
                             help_key, "Main Python Documentation")
                         interpreter.HelpPath = help_path
                         app_debugLogger.info(
                             "interpreter %s,help path is %s",
                             interpreter.Name, interpreter.HelpPath)
                     except Exception as e:
                         app_debugLogger.error(
                             "read python child regkey %s\\xxx\\%s error:%s",
                             ROOT_KEY_NAMES[k], name, e)
                         continue
             except Exception as e:
                 app_debugLogger.error(
                     "load python interpreter from regkey %s error:%s",
                     ROOT_KEY_NAMES[k], e)
                 continue
     else:
         executable_path = sys.executable
         install_path = os.path.dirname(executable_path)
         interpreter = Interpreter.PythonInterpreter(
             "default", executable_path)
         self.interpreters.append(interpreter)
예제 #11
0
 def ChangeDir(self, event):
     path = self.dirControl.GetValue().strip()
     if path == "":
         self._treeCtrl.DeleteAllItems()
         return
     if sysutilslib.isWindows():
         path = path.replace("/", os.sep)
     self.ListDirItemFiles(path.rstrip(os.sep))
예제 #12
0
 def GetDocPath(self):
     if self._help_path == "":
         if sysutils.isWindows():
             python_location = os.path.dirname(self.Path)
             doc_location = os.path.join(python_location, "Doc")
             file_list = glob.glob(os.path.join(doc_location, "*.chm"))
             if len(file_list) > 0:
                 self._help_path = file_list[0]
예제 #13
0
 def __init__(self):
     self.data_root_path = os.path.join(appdirs.getAppDataFolder(),"intellisence")
     if sysutilslib.isWindows():
         self._builtin_data_path = os.path.join(self.data_root_path,"builtins")
     else:
         self._builtin_data_path = os.path.join(sysutilslib.mainModuleDir, "noval", "tool", "data","intellisence","builtins")
     self.module_dicts = {}
     self._loader = IntellisenceDataLoader(self.data_root_path,self._builtin_data_path,self)
     self._is_running = False
     self._process_obj = None
예제 #14
0
 def FindFile(self, filePath):
     if filePath:
         for file in self._files:
             if sysutilslib.isWindows():
                 if file.filePath.lower() == filePath.lower():
                     return file
             else:
                 if file.filePath == filePath:
                     return file
     return None
예제 #15
0
def open_path_in_terminator(file_path):
    import locale
    sys_encoding = locale.getdefaultlocale()[1]
    if sysutils.isWindows():
        subprocess.Popen('start cmd.exe',
                         shell=True,
                         cwd=file_path.encode(sys_encoding))
    else:
        subprocess.Popen('gnome-terminal',
                         shell=True,
                         cwd=file_path.encode(sys_encoding))
예제 #16
0
def _getSystemDir(kind):
    if (kind == AG_LOGS_DIR):
        return os.path.join(getSystemDir(AG_SYSTEM_DIR), "logs")
    elif (kind == AG_DEMOS_DIR):
        return os.path.join(getSystemDir(AG_SYSTEM_DIR), "demos")
    else:
        path = ""
        if (sysutils.isServer()):
            path = os.getenv("ACTIVEGRID_SERVER_HOME")
            if ((path is None) or (len(path) < 1)):
                path = sysutils.mainModuleDir
        else:
            path = os.getenv("AG_DOCUMENTS_DIR")
            if ((path is None) or (len(path) < 1)):
                if sysutils.isWindows():
                    ifDefPy()
                    try:
                        from win32com.shell import shell, shellcon
                        path = shell.SHGetFolderPath(0,
                                                     shellcon.CSIDL_PERSONAL,
                                                     None, 0)
                    except:
                        pass
                    endIfDef()
                    if ((path is None) or (len(path) < 1)):
                        homedrive = asString(os.getenv("HOMEDRIVE"))
                        homepath = os.getenv("HOMEPATH")
                        ##                        if ((homedrive is not None) and (len(homedrive) > 0) and (homepath is not None) and (len(homepath) > 0)):
                        path = os.path.join(homedrive, homepath, "MYDOCU~1")
                else:
                    ifDefPy()
                    if sys.platform == "darwin":
                        try:
                            import macfs
                            import MACFS
                            fsspec_disk, fsspec_desktop = macfs.FindFolder(
                                MACFS.kOnSystemDisk,
                                MACFS.kDocumentsFolderType, 0)
                            path = macfs.FSSpec((fsspec_disk, fsspec_desktop,
                                                 '')).as_pathname()
                        except:
                            pass
                    endIfDef()

                ifDefPy()
                if ((path is None) or (len(path) < 1)):
                    path = os.path.expanduser("~")
                endIfDef()
                if ((path is None) or (len(path) < 1)):
                    path = "/"
                path = os.path.join(path, "NovalIDE")

        return path
예제 #17
0
    def SetRootDir(self, directory):
        if not os.path.isdir(directory):
            raise Exception("%s is not a valid directory" % directory)

        self._view.dir_ctrl.DeleteChildren(self._view.dir_ctrl.GetRootItem())
        self._view.dir_ctrl.DeleteAllItems()

        # add directory as root
        root = self._view.dir_ctrl.AddRoot(directory.replace(":", ""))
        if sysutils.isWindows():
            directory += os.sep
        self.LoadDir(root, directory)
예제 #18
0
 def GetPipPath(self):
     if sysutils.isWindows():
         pip_name = "pip.exe"
     else:
         pip_name = "pip"
     python_location = os.path.dirname(self.Path)
     pip_path_list = [
         os.path.join(python_location, "Scripts", pip_name),
         os.path.join(python_location, pip_name)
     ]
     for pip_path in pip_path_list:
         if os.path.exists(pip_path):
             return pip_path
     return None
예제 #19
0
    def parse_project(self, doc):
        assert (doc != None)
        project = doc.GetModel()
        interpreter_path = project.Interpreter.Path
        interpreter = interpretermanager.InterpreterManager(
        ).GetInterpreterByPath(interpreter_path)
        if interpreter is None:
            return
        project_location = os.path.dirname(doc.GetFilename())
        path_list = [project_location]
        metadata_path = os.path.join(project_location, ".metadata")
        intellisence_data_path = os.path.join(metadata_path,
                                              str(interpreter.Id))
        self.last_update_time = self.get_last_update(intellisence_data_path)
        if not os.path.exists(intellisence_data_path):
            parserutils.MakeDirs(intellisence_data_path)
            #hidden intellisence data path on windows and linux
            if sysutilslib.isWindows():
                import win32api
                import win32con
                win32api.SetFileAttributes(metadata_path,
                                           win32con.FILE_ATTRIBUTE_HIDDEN)

        update_file_count = 0
        for filepath in project.filePaths:
            if self._stop:
                break
            file_dir = os.path.dirname(filepath)
            is_package_dir = fileparser.is_package_dir(file_dir)
            if is_package_dir or parserutils.PathsContainPath(
                    path_list, file_dir):
                ext = strutils.GetFileExt(filepath)
                if ext in ['py', 'pyw']:
                    mk_time = os.path.getmtime(filepath)
                    relative_module_name, is_package = parserutils.get_relative_name(
                        filepath, path_list)
                    if mk_time > self.last_update_time or not os.path.exists(
                            os.path.join(intellisence_data_path,
                                         relative_module_name + ".$members")):
                        app_debugLogger.debug('update file %s ,relative module name is %s',\
                                    filepath,parserutils.get_relative_name(filepath,path_list)[0])
                        fileparser.dump(filepath, relative_module_name,
                                        intellisence_data_path, is_package)
                        update_file_count += 1
            else:
                app_debugLogger.debug('%s is not valid parse dir', file_dir)
        app_debugLogger.debug('total update %d files', update_file_count)
        if update_file_count > 0:
            self.update_last_time(intellisence_data_path)
예제 #20
0
 def GetVirtualEnvPath(self, interpreter):
     if sysutils.isWindows():
         virtualenv_name = "virtualenv.exe"
     else:
         virtualenv_name = "virtualenv"
     python_location = os.path.dirname(interpreter.Path)
     virtualenv_path_list = [
         os.path.join(python_location, "Scripts", virtualenv_name),
         os.path.join(python_location, virtualenv_name)
     ]
     for virtualenv_path in virtualenv_path_list:
         if os.path.exists(virtualenv_path):
             return virtualenv_path
     virtualenv_path = whichpath.GuessPath(virtualenv_name)
     return virtualenv_path
예제 #21
0
 def ChooseExecutablePath(self, event):
     if sysutils.isWindows():
         descr = _("Executable (*.exe) |*.exe")
     else:
         descr = "All Files (*)|*"
     dlg = wx.FileDialog(self,
                         _("Select Executable Path"),
                         wildcard=descr,
                         style=wx.OPEN | wx.FILE_MUST_EXIST | wx.CHANGE_DIR)
     if dlg.ShowModal() == wx.ID_OK:
         path = dlg.GetPath()
         self.path_ctrl.SetValue(path)
         self.name_ctrl.SetValue(path)
         self.path_ctrl.SetInsertionPointEnd()
     dlg.Destroy()
예제 #22
0
 def OpenCommandLineArgs(self):
     """
     Called to open files that have been passed to the application from the
     command line.
     """
     args = sys.argv[1:]
     for arg in args:
         if (wx.Platform != "__WXMSW__" or arg[0] != "/") and arg[0] != '-' and os.path.exists(arg):
             if sysutilslib.isWindows():
                 arg = arg.decode("gbk")
             else:
                 arg = arg.decode("utf-8")
             self.GetDocumentManager().CreateDocument(os.path.normpath(arg), wx.lib.docview.DOC_SILENT)
             if strutils.GetFileExt(arg) == PROJECT_SHORT_EXTENSION:
                 self._open_project_path = arg
예제 #23
0
    def SetRootDir(self, directory):
        if not os.path.isdir(directory):
            raise Exception("%s is not a valid directory" % directory)

        self._view.dir_ctrl.DeleteChildren(self._view.dir_ctrl.GetRootItem())
        self._view.dir_ctrl.DeleteAllItems()

        # add directory as root
        root = self._view.dir_ctrl.AddRoot(directory.replace(":", ""))
        if sysutils.isWindows():
            directory += os.sep
##     self._view.dir_ctrl.SetPyData(root, Directory(directory))
### project_view.dir_ctrl.SetItemImage(root, self.iconentries['directory'])
##   self._view.dir_ctrl.Expand(root)
        self.LoadDir(root, directory)
예제 #24
0
 def OpenInterpreter(self, event):
     interpreter = wx.GetApp().GetCurrentInterpreter()
     if interpreter is None:
         return
     try:
         if sysutilslib.isWindows():
             fileutils.start_file(interpreter.Path)
         else:
             cmd_list = [
                 'gnome-terminal', '-x', 'bash', '-c', interpreter.Path
             ]
             subprocess.Popen(cmd_list, shell=False)
     except Exception as e:
         wx.MessageBox(
             _("%s") % str(e), _("Open Error"), wx.OK | wx.ICON_ERROR,
             wx.GetApp().GetTopWindow())
예제 #25
0
 def __init__(self):
     if sysutilslib.isWindows():
         pythoncom.CoInitialize()
     db_dir = os.path.join(appdirs.getAppDataFolder(),"cache")
     if not os.path.exists(db_dir):
         parserutils.MakeDirs(db_dir)
     self.data_id = None
     self.user_id = None
     db_path = os.path.join(db_dir,self.USER_DATA_DB_NAME)
     super(UserDataDb,self).__init__(db_path)
     self.init_data_db()
     if parserutils.CompareDatabaseVersion(self.DB_VERSION,self.GetDbVersion()):
         self.close()
         os.remove(db_path)
         BaseDb.__init__(self,db_path)
         self.init_data_db()
예제 #26
0
def parameterizePathWithAGSystemVar(inpath):
    """Returns parameterized path if path starts with a known AG directory. Otherwise returns path as it was passed in."""
    _initAGSystemVars()
    path = inpath
    if not sysutils.isWindows():
        # ensure we have forward slashes
        path = path.replace("\\", "/")

    path = os.path.abspath(path)

    for varname in AG_SYSTEM_VARS_LENGTH_ORDER:
        varval = EXPANDED_AG_SYSTEM_VARS[varname]
        if path.startswith(varval):
            return path.replace(varval, varname)

    return inpath
예제 #27
0
파일: IDE.py 프로젝트: ver007/NovalIDE
    def SelectDocumentPath(self, templates, flags, save):
        """
        Under Windows, pops up a file selector with a list of filters
        corresponding to document templates. The wxDocTemplate corresponding
        to the selected file's extension is returned.

        On other platforms, if there is more than one document template a
        choice list is popped up, followed by a file selector.

        This function is used in wxDocManager.CreateDocument.
        """
        descr = ''
        for temp in templates:
            if temp.IsVisible():
                if len(descr) > 0:
                    descr = descr + _('|')
                descr = descr + temp.GetDescription() + _(
                    " ("
                ) + temp.GetFileFilter() + _(") |") + temp.GetFileFilter(
                )  # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk
        if sysutilslib.isWindows():
            descr = _(
                "All Files(*.*)|*.*|%s"
            ) % descr  # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk
        else:
            descr = _("All Files (*)|*|%s") % descr

        dlg = wx.FileDialog(self.FindSuitableParent(),
                            _("Select a File"),
                            wildcard=descr,
                            style=wx.OPEN | wx.FILE_MUST_EXIST | wx.CHANGE_DIR)
        # dlg.CenterOnParent()  # wxBug: caused crash with wx.FileDialog
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
        else:
            path = None
        dlg.Destroy()

        if path:
            theTemplate = self.FindTemplateForPath(path)
            return (theTemplate, path)

        return (None, None)
예제 #28
0
    def __init__(self, parent, dlg_id, title):
        wx.Dialog.__init__(self, parent, dlg_id, title)
        contentSizer = wx.BoxSizer(wx.VERTICAL)

        lineSizer = wx.BoxSizer(wx.HORIZONTAL)
        lineSizer.Add(wx.StaticText(self, -1, _("Interpreter Path:")), 0,
                      wx.ALIGN_CENTER | wx.LEFT, HALF_SPACE)
        self.path_ctrl = wx.TextCtrl(self, -1, "", size=(200, -1))
        if sysutils.isWindows():
            self.path_ctrl.SetToolTipString(
                _("set the location of python.exe or pythonw.exe"))
        else:
            self.path_ctrl.SetToolTipString(
                _("set the location of python interpreter"))
        lineSizer.Add(self.path_ctrl, 0, wx.LEFT | wx.ALIGN_BOTTOM, HALF_SPACE)

        self.browser_btn = wx.Button(self, -1, _("Browse..."))
        wx.EVT_BUTTON(self.browser_btn, -1, self.ChooseExecutablePath)
        lineSizer.Add(self.browser_btn, 0, wx.LEFT | wx.ALIGN_BOTTOM,
                      HALF_SPACE)
        contentSizer.Add(lineSizer, 0, wx.ALL, HALF_SPACE)

        lineSizer = wx.BoxSizer(wx.HORIZONTAL)
        lineSizer.Add(wx.StaticText(self, -1, _("Interpreter Name:")), 0,
                      wx.ALIGN_CENTER | wx.LEFT, HALF_SPACE)
        self.name_ctrl = wx.TextCtrl(self, -1, "", size=(190, -1))
        self.name_ctrl.SetToolTipString(
            _("set the name of python interpreter"))
        lineSizer.Add(self.name_ctrl, 0, wx.LEFT, HALF_SPACE)
        contentSizer.Add(lineSizer, 0, wx.ALL, HALF_SPACE)

        bsizer = wx.StdDialogButtonSizer()
        ok_btn = wx.Button(self, wx.ID_OK, _("&OK"))
        ok_btn.SetDefault()
        bsizer.AddButton(ok_btn)
        cancel_btn = wx.Button(self, wx.ID_CANCEL, _("&Cancel"))
        bsizer.AddButton(cancel_btn)
        bsizer.Realize()
        contentSizer.Add(bsizer, 0, wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM,
                         HALF_SPACE)
        self.SetSizer(contentSizer)
        self.Fit()
예제 #29
0
 def Install(self, app_path):
     if sysutilslib.isWindows():
         os.startfile(app_path)
     else:
         path = os.path.dirname(sys.executable)
         pip_path = os.path.join(path, "pip")
         cmd = "%s  -c \"from distutils.sysconfig import get_python_lib; print get_python_lib()\"" % (
             sys.executable, )
         python_lib_path = Interpreter.GetCommandOutput(cmd).strip()
         user = getpass.getuser()
         should_root = not fileutils.is_writable(python_lib_path, user)
         if should_root:
             cmd = "pkexec " + "%s install %s" % (pip_path, app_path)
         else:
             cmd = "%s install %s" % (pip_path, app_path)
         subprocess.call(cmd, shell=True)
         app_startup_path = whichpath.GuessPath("NovalIDE")
         #wait a moment to avoid single instance limit
         subprocess.Popen("/bin/sleep 2;%s" % app_startup_path, shell=True)
     wx.GetApp().MainFrame.OnExit(None)
예제 #30
0
 def generate_intellisence_data(self,interpreter,progress_dlg = None,load_data_end=False):
     if interpreter.IsBuiltIn:
         return
     sys_path_list = interpreter.SysPathList
     script_path = os.path.join(sysutilslib.mainModuleDir, "noval", "parser", "factory.py")
     database_version = config.DATABASE_VERSION
     cmd_list = [interpreter.Path,script_path,os.path.join(self.data_root_path,str(interpreter.Id)),\
                 database_version]
     if sysutilslib.isWindows():
         startupinfo = subprocess.STARTUPINFO()
         startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
         startupinfo.wShowWindow = subprocess.SW_HIDE
     else:
         startupinfo = None
     self._process_obj = subprocess.Popen(cmd_list,startupinfo=startupinfo,cwd=os.path.join(sysutilslib.mainModuleDir, "noval", "parser"))
     interpreter.Analysing = True
     self._is_running = interpreter.Analysing
     #if current interpreter is analysing,load data at end
     if interpreter == interpretermanager.InterpreterManager().GetCurrentInterpreter():
         load_data_end = True
     self.Wait(interpreter,progress_dlg,load_data_end)