Python源码示例:jedi.Script()

示例1
def _get_completions(source, func, line=None, column=None):
    try:
        num_lines = len(source.split('\n'))
        if line is None:
            line = num_lines
        s = Script(source, line=line, column=column)
        completions = s.completions()
        # print('### input:')
        # print(source)
        # print('### completions:')
        # print('\n'.join([c.name for c in completions]))
    except:
        print('Exception in completions thread')
        traceback.print_exc()
        completions = []

    mainthread(WrappablePartial(func, [c for c in completions]))() 
示例2
def _get_defs(source, func, line=None, column=None):
    error = None
    try:
        num_lines = len(source.split('\n'))
        if line is None:
            line = num_lines
        s = Script(source, line=line, column=column)
        defs = s.goto_definitions()
        sigs = s.call_signatures()
    except:
        print('Exception in defs thread')
        traceback.print_exc()
        defs = []
        sigs = []
        error = 'Could not retrieve docstring'

    mainthread(WrappablePartial(func, defs, sigs, error=error))() 
示例3
def goto_assignments(request_data):
    """
    Go to assignements worker.
    """
    code = request_data['code']
    line = request_data['line'] + 1
    column = request_data['column']
    path = request_data['path']
    # encoding = request_data['encoding']
    encoding = 'utf-8'
    script = jedi.Script(code, line, column, path, encoding)
    try:
        definitions = script.goto_assignments()
    except jedi.NotFoundError:
        pass
    else:
        ret_val = [(d.module_path, d.line - 1 if d.line else None,
                    d.column, d.full_name)
                   for d in definitions]
        return ret_val 
示例4
def quick_doc(request_data):
    """
    Worker that returns the documentation of the symbol under cursor.
    """
    code = request_data['code']
    line = request_data['line'] + 1
    column = request_data['column']
    path = request_data['path']
    # encoding = 'utf-8'
    encoding = 'utf-8'
    script = jedi.Script(code, line, column, path, encoding)
    try:
        definitions = script.goto_definitions()
    except jedi.NotFoundError:
        return []
    else:
        ret_val = [d.doc for d in definitions]
        return ret_val 
示例5
def complete(code, line, column, path, encoding, prefix):
        """
        Completes python code using `jedi`_.

        :returns: a list of completion.
        """
        ret_val = []
        try:
            script = jedi.Script(code, line + 1, column, path, encoding)
            completions = script.completions()
            print('completions: %r' % completions)
        except jedi.NotFoundError:
            completions = []
        for completion in completions:
            ret_val.append({
                'name': completion.name,
                'icon': icon_from_typename(
                    completion.name, completion.type),
                'tooltip': completion.description})
        return ret_val 
示例6
def goto_definition(event):
    if not control_is_pressed(event.state):
        return

    assert isinstance(event.widget, tk.Text)
    text = event.widget

    source = text.get("1.0", "end")
    index = text.index("insert")
    index_parts = index.split(".")
    line, column = int(index_parts[0]), int(index_parts[1])
    # TODO: find current editor filename
    from jedi import Script

    script = Script(source, line=line, column=column, path="")
    defs = script.goto_definitions()
    if len(defs) > 0:
        module_path = defs[0].module_path
        module_name = defs[0].module_name
        line = defs[0].line
        if module_path and line is not None:
            get_workbench().get_editor_notebook().show_file(module_path, line)
        elif module_name == "" and line is not None:  # current editor
            get_workbench().get_editor_notebook().get_current_editor().select_range(line) 
示例7
def finddocstring(self):
        ''' find the docstring at current cursor location
        '''
        import StringIO
        from jedi import Script

        i=editor.get_selection()
        t=editor.get_text()
        (line,txt)=[(line,n) for (line,n) in enumerate(StringIO.StringIO(editor.get_text()[:i[1]]))][-1]
        script = Script(t, line+1, len(txt))

        dfn = script.goto_definitions()
        if dfn:
            doc=dfn[0].doc
            import ui
            v=ui.TextView()
            v.width=100
            v.height=50
            v.text=doc
            editor._set_toolbar(v) 
示例8
def getJediScript(code, srcPath):
    """Provides the jedi Script object considering the current project"""
    if not os.path.isabs(srcPath):
        # Pretend it is in the user home dir
        srcPath = os.path.realpath(QDir.homePath()) + os.path.sep + srcPath
    return jedi.Script(code=code, path=srcPath, project=getJediProject()) 
示例9
def __init__(self, area, *args, **kwargs):
        source      = area.get('1.0', 'end')
        line, col   = area.indexref()
        script      = Script(source, line, col, area.filename)
        completions = script.completions()
        CompletionWindow.__init__(self, area, completions, *args, **kwargs) 
示例10
def parseText(self):
        if self.completer:
            text = self.toPlainText()
            self.moveCompleter()
            if text:
                tc = self.textCursor()
                context_completer = False
                pos = tc.position()
                if managers.context in managers.contextCompleters:
                    line = text[:pos].split('\n')[-1]
                    comp, extra = managers.contextCompleters[managers.context ](line)
                    if comp or extra:
                        context_completer = True
                        self.completer.updateCompleteList(comp, extra)
                if not context_completer:
                    if re.match('[a-zA-Z0-9.]', text[pos-1]):
                        offs = 0
                        if managers.context in managers.autoImport:
                            autoImp = managers.autoImport.get(managers.context, '')
                            text = autoImp + text
                            offs = len(autoImp.split('\n'))-1
                        bl = tc.blockNumber() + 1 + offs
                        col = tc.columnNumber()
                        script = jedi.Script(text, bl, col, '')
                        try:
                            # curframe = inspect.currentframe()
                            # print inspect.getouterframes(curframe, 2)[1][3]
                            self.completer.updateCompleteList(script.completions())
                        except:
                            self.completer.updateCompleteList()
                        return
                    else:
                        self.completer.updateCompleteList()
            else:
                self.completer.updateCompleteList() 
示例11
def _get_jedi_script(request_data):
    return jedi.Script(request_data['source'],
                       request_data['line'],
                       request_data['col'],
                       request_data['source_path']) 
示例12
def calltips(request_data):
    """
    Worker that returns a list of calltips.

    A calltips is a tuple made of the following parts:
      - module_name: name of the module of the function invoked
      - call_name: name of the function that is being called
      - params: the list of parameter names.
      - index: index of the current parameter
      - bracket_start

    :returns tuple(module_name, call_name, params)
    """
    code = request_data['code']
    line = request_data['line'] + 1
    column = request_data['column']
    path = request_data['path']
    # encoding = request_data['encoding']
    encoding = 'utf-8'
    # use jedi to get call signatures
    script = jedi.Script(code, line, column, path, encoding)
    signatures = script.call_signatures()
    for sig in signatures:
        results = (str(sig.module_name), str(sig.name),
                   [p.description for p in sig.params], sig.index,
                   sig.bracket_start, column)
        # todo: add support for multiple signatures, for that we need a custom
        # widget for showing calltips.
        return results
    return [] 
示例13
def parseText(self):
        if self.completer:
            text = self.toPlainText()
            self.moveCompleter()
            if text:
                tc = self.textCursor()
                context_completer = False
                pos = tc.position()
                if managers.context in managers.contextCompleters:
                    line = text[:pos].split('\n')[-1]
                    comp, extra = managers.contextCompleters[managers.context ](line)
                    if comp or extra:
                        context_completer = True
                        self.completer.updateCompleteList(comp, extra)
                if not context_completer:
                    if re.match('[a-zA-Z0-9.]', text[pos-1]):
                        offs = 0
                        if managers.context in managers.autoImport:
                            autoImp = managers.autoImport.get(managers.context, '')
                            text = autoImp + text
                            offs = len(autoImp.split('\n'))-1
                        bl = tc.blockNumber() + 1 + offs
                        col = tc.columnNumber()
                        script = jedi.Script(text, bl, col, '')
                        try:
                            # curframe = inspect.currentframe()
                            # print inspect.getouterframes(curframe, 2)[1][3]
                            self.completer.updateCompleteList(script.completions())
                        except:
                            self.completer.updateCompleteList()
                        return
                    else:
                        self.completer.updateCompleteList()
            else:
                self.completer.updateCompleteList() 
示例14
def _start_linter():
    """
    This is a pre-alpha API. You're not supposed to use it at all, except for
    testing. It will very likely change.
    """
    import jedi

    if '--debug' in sys.argv:
        jedi.set_debug_function()

    for path in sys.argv[2:]:
        if path.startswith('--'):
            continue
        if isdir(path):
            import fnmatch
            import os

            paths = []
            for root, dirnames, filenames in os.walk(path):
                for filename in fnmatch.filter(filenames, '*.py'):
                    paths.append(os.path.join(root, filename))
        else:
            paths = [path]

        try:
            for path in paths:
                for error in jedi.Script(path=path)._analysis():
                    print(error)
        except Exception:
            if '--pdb' in sys.argv:
                import traceback
                traceback.print_exc()
                import pdb
                pdb.post_mortem()
            else:
                raise 
示例15
def parse_source(source):
    try:
        import parso

        return parso.parse(source)
    except ImportError:
        import jedi

        script = jedi.Script(source)
        return get_module_node(script) 
示例16
def _cmd_editor_autocomplete(self, cmd):
        error = None
        try:
            import jedi

            self._debug(jedi.__file__, sys.path)
            with warnings.catch_warnings():
                script = jedi.Script(cmd.source, cmd.row, cmd.column, cmd.filename)
                completions = self._export_completions(script.completions())

        except ImportError:
            completions = []
            error = "Could not import jedi"
        except Exception as e:
            completions = []
            error = "Autocomplete error: " + str(e)

        return InlineResponse(
            "editor_autocomplete",
            source=cmd.source,
            row=cmd.row,
            column=cmd.column,
            filename=cmd.filename,
            completions=completions,
            error=error,
        ) 
示例17
def _cmd_editor_autocomplete(self, cmd):
        # template for the response
        result = dict(source=cmd.source, row=cmd.row, column=cmd.column)

        try:
            import jedi

            script = jedi.Script(cmd.source, cmd.row, cmd.column, sys_path=[self._api_stubs_path])
            completions = script.completions()
            result["completions"] = self._filter_completions(completions)
        except Exception:
            traceback.print_exc()
            result["error"] = "Autocomplete error"

        return result 
示例18
def __init__(self, source=None, line=None, column=None, path=None,
				encoding='utf-8', sys_path=None, environment=None,
				_project=None):
		jedi.Script.__init__(self, source, line, column, path, encoding, sys_path, environment, _project) 
示例19
def autocomplete(self, source, cursor):
        """ Return a list of autocomplete suggestions for the given text.
        Results are based on the modules loaded.

        Parameters
        ----------
            source: str
                Source code to autocomplete
            cursor: (line, column)
                Position of the editor
        Return
        ------
            result: list
                List of autocompletion strings
        """
        return []
        try:
            #: TODO: Move to separate process
            line, column = cursor
            script = jedi.Script(source, line+1, column,
                                 sys_path=self.sys_path)

            #: Get suggestions
            results = []
            for c in script.completions():
                results.append(c.name)

                #: Try to get a signature if the docstring matches
                #: something Scintilla will use (ex "func(..." or "Class(...")
                #: Scintilla ignores docstrings without a comma in the args
                if c.type in ['function', 'class', 'instance']:
                    docstring = c.docstring()

                    #: Remove self arg
                    docstring = docstring.replace("(self,", "(")

                    if docstring.startswith("{}(".format(c.name)):
                        results.append(docstring)
                        continue

            return results
        except Exception:
            #: Autocompletion may fail for random reasons so catch all errors
            #: as we don't want the editor to exit because of this
            return [] 
示例20
def _cmd_shell_autocomplete(self, cmd):
        source = cmd.source

        # TODO: combine dynamic results and jedi results
        if source.strip().startswith("import ") or source.strip().startswith("from "):
            # this needs the power of jedi
            response = {"source": cmd.source}

            try:
                import jedi

                # at the moment I'm assuming source is the code before cursor, not whole input
                lines = source.split("\n")
                script = jedi.Script(
                    source, len(lines), len(lines[-1]), sys_path=[self._api_stubs_path]
                )
                completions = script.completions()
                response["completions"] = self._filter_completions(completions)
            except Exception:
                traceback.print_exc()
                response["error"] = "Autocomplete error"

            return response
        else:
            # use live data
            match = re.search(
                r"(\w+\.)*(\w+)?$", source
            )  # https://github.com/takluyver/ubit_kernel/blob/master/ubit_kernel/kernel.py
            if match:
                prefix = match.group()
                if "." in prefix:
                    obj, prefix = prefix.rsplit(".", 1)
                    names = self._evaluate(
                        "dir({}) if '{}' in locals() or '{}' in globals() else []".format(
                            obj, obj, obj
                        )
                    )
                else:
                    names = self._evaluate("dir()")
            else:
                names = []
                prefix = ""

            completions = []

            # prevent TypeError (iterating over None)
            names = names if names else []

            for name in names:
                if name.startswith(prefix) and not name.startswith("__"):
                    completions.append({"name": name, "complete": name[len(prefix) :]})

            return {"completions": completions, "source": source}