Exemple #1
0
def get_list_pyenv_envs():
    """Return the list of all pyenv envs found in the system."""
    global PYENV_ENV_LIST_CACHE

    env_list = {}
    pyenv = find_program('pyenv')
    if pyenv is None:
        return env_list

    cmdstr = ' '.join([pyenv, 'versions', '--bare', '--skip-aliases'])
    try:
        out, __ = run_shell_command(cmdstr, env={}).communicate()
        out = out.decode().strip()
    except Exception:
        return env_list

    out = out.split('\n') if out else []
    for env in out:
        data = env.split(osp.sep)
        path = get_pyenv_path(data[-1])

        name = f'pyenv: {data[-1]}'
        version = f'Python {data[0]}'
        env_list[name] = (path, version)

    PYENV_ENV_LIST_CACHE = env_list
    return env_list
Exemple #2
0
def get_list_pyenv_envs():
    """Return the list of all pyenv envs found in the system."""
    global PYENV_ENV_LIST_CACHE

    env_list = {}
    pyenv = find_program('pyenv')
    if pyenv is None:
        return env_list

    cmdstr = ' '.join([pyenv, 'versions', '--bare', '--skip-aliases'])
    try:
        out, __ = run_shell_command(cmdstr, env={}).communicate()
        out = out.decode()
    except Exception:
        out = ''

    out = out.split('\n')
    for env in out:
        data = env.split(osp.sep)
        path = get_pyenv_path(data[-1])

        if data[-1] == '':
            name = 'internal' if running_in_mac_app(path) else 'system'
        else:
            name = 'pyenv: {}'.format(data[-1])
        version = ('Python 2.7'
                   if data[-1] == '' else 'Python {}'.format(data[0]))
        env_list[name] = (path, version)

    PYENV_ENV_LIST_CACHE = env_list
    return env_list
Exemple #3
0
def get_list_conda_envs():
    """Return the list of all conda envs found in the system."""
    global CONDA_ENV_LIST_CACHE

    env_list = {}
    conda = find_conda()
    if conda is None:
        return env_list

    cmdstr = ' '.join([conda, 'env', 'list', '--json'])
    try:
        out, __ = run_shell_command(cmdstr, env={}).communicate()
        out = out.decode()
        out = json.loads(out)
    except Exception:
        out = {'envs': []}

    for env in out['envs']:
        name = env.split(osp.sep)[-1]
        path = osp.join(env, 'python.exe') if WINDOWS else osp.join(
            env, 'bin', 'python')

        try:
            version, __ = run_program(path, ['--version']).communicate()
            version = version.decode()
        except Exception:
            version = ''

        name = ('base' if name.lower().startswith('anaconda')
                or name.lower().startswith('miniconda') else name)
        name = 'conda: {}'.format(name)
        env_list[name] = (path, version.strip())

    CONDA_ENV_LIST_CACHE = env_list
    return env_list
Exemple #4
0
def evalsc(command):
    """Evaluate special commands
    (analog to IPython's magic commands but far less powerful/complete)"""
    assert command.startswith('%')
    from spyder.utils import programs

    namespace = _get_globals()
    command = command[1:].strip()  # Remove leading %

    import re
    clear_match = re.match(r"^clear ([a-zA-Z0-9_, ]+)", command)
    cd_match = re.match(r"^cd \"?\'?([a-zA-Z0-9_\ \:\\\/\.]+)", command)

    if cd_match:
        os.chdir(eval('r"%s"' % cd_match.groups()[0].strip()))
    elif clear_match:
        varnames = clear_match.groups()[0].replace(' ', '').split(',')
        for varname in varnames:
            try:
                namespace.pop(varname)
            except KeyError:
                pass
    elif command in ('cd', 'pwd'):
        try:
            _print(os.getcwdu())
        except AttributeError:
            _print(os.getcwd())
    elif command == 'ls':
        if os.name == 'nt':
            programs.run_shell_command('dir')
            _print('\n')
        else:
            programs.run_shell_command('ls')
            _print('\n')
    elif command == 'scientific':
        from spyder.config import base
        execfile(base.SCIENTIFIC_STARTUP, namespace)
    else:
        raise NotImplementedError("Unsupported command: '%s'" % command)
Exemple #5
0
def evalsc(command):
    """Evaluate special commands
    (analog to IPython's magic commands but far less powerful/complete)"""
    assert command.startswith('%')
    from spyder.utils import programs

    namespace = _get_globals()
    command = command[1:].strip()  # Remove leading %

    import re
    clear_match = re.match(r"^clear ([a-zA-Z0-9_, ]+)", command)
    cd_match = re.match(r"^cd \"?\'?([a-zA-Z0-9_\ \:\\\/\.]+)", command)

    if cd_match:
        os.chdir(eval('r"%s"' % cd_match.groups()[0].strip()))
    elif clear_match:
        varnames = clear_match.groups()[0].replace(' ', '').split(',')
        for varname in varnames:
            try:
                namespace.pop(varname)
            except KeyError:
                pass
    elif command in ('cd', 'pwd'):
        try:
            _print(os.getcwdu())
        except AttributeError:
            _print(os.getcwd())
    elif command == 'ls':
        if os.name == 'nt':
            programs.run_shell_command('dir')
            _print('\n')
        else:
            programs.run_shell_command('ls')
            _print('\n')
    elif command == 'scientific':
        from spyder.config import base
        execfile(base.SCIENTIFIC_STARTUP, namespace)
    else:
        raise NotImplementedError("Unsupported command: '%s'" % command)
Exemple #6
0
def get_pylint_version():
    """Return pylint version"""
    if PYLINT_PATH is None:
        return
    cwd = osp.dirname(PYLINT_PATH)
    args = ['--version']
    if os.name == 'nt':
        cmd = ' '.join([PYLINT] + args)
        process = programs.run_shell_command(cmd, cwd=cwd)
    else:
        process = programs.run_program(PYLINT, args, cwd=cwd)
    lines = to_unicode_from_fs(process.stdout.read()).splitlines()
    if lines:
        regex = '({0}*|pylint-script.py) ([0-9\.]*)'.format(PYLINT)
        match = re.match(regex, lines[0])
        if match is not None:
            return match.groups()[1]
Exemple #7
0
def get_pylint_version():
    """Return pylint version"""
    if PYLINT_PATH is None:
        return
    cwd = osp.dirname(PYLINT_PATH)
    args = ['--version']
    if os.name == 'nt':
        cmd = ' '.join([PYLINT] + args)
        process = programs.run_shell_command(cmd, cwd=cwd)
    else:
        process = programs.run_program(PYLINT, args, cwd=cwd)
    lines = to_unicode_from_fs(process.stdout.read()).splitlines()
    if lines:
        regex = '({0}*|pylint-script.py) ([0-9\.]*)'.format(PYLINT)
        match = re.match(regex, lines[0])
        if match is not None:
            return match.groups()[1]
Exemple #8
0
 def find_files_in_hg_manifest(self):
     p = programs.run_shell_command('hg manifest', cwd=self.rootpath)
     hgroot = get_vcs_root(self.rootpath)
     self.pathlist = [hgroot]
     for path in p.stdout.read().decode().splitlines():
         with QMutexLocker(self.mutex):
             if self.stopped:
                 return False
         dirname = osp.dirname(path)
         try:
             if re.search(self.exclude, dirname+os.sep):
                 continue
             filename = osp.basename(path)
             if re.search(self.exclude, filename):
                 continue
             if re.search(self.include, filename):
                 self.filenames.append(osp.join(hgroot, path))
         except re.error:
             self.error_flag = _("invalid regular expression")
             return False
     return True
Exemple #9
0
    def run_command(self, cmd, new_prompt=True):
        """Run command in interpreter"""
        if cmd == 'exit()':
            self.exit_flag = True
            self.write('\n')
            return
        # -- Special commands type I
        #    (transformed into commands executed in the interpreter)
        # ? command
        special_pattern = r"^%s (?:r\')?(?:u\')?\"?\'?([a-zA-Z0-9_\.]+)"
        run_match = re.match(special_pattern % 'run', cmd)
        help_match = re.match(r'^([a-zA-Z0-9_\.]+)\?$', cmd)
        cd_match = re.match(r"^\!cd \"?\'?([a-zA-Z0-9_ \.]+)", cmd)
        if help_match:
            cmd = 'help(%s)' % help_match.group(1)
        # run command
        elif run_match:
            filename = guess_filename(run_match.groups()[0])
            cmd = "runfile('%s', args=None)" % remove_backslashes(filename)
        # !cd system command
        elif cd_match:
            cmd = 'import os; os.chdir(r"%s")' % cd_match.groups()[0].strip()
        # -- End of Special commands type I
            
        # -- Special commands type II
        #    (don't need code execution in interpreter)
        xedit_match = re.match(special_pattern % 'xedit', cmd)
        edit_match = re.match(special_pattern % 'edit', cmd)
        clear_match = re.match(r"^clear ([a-zA-Z0-9_, ]+)", cmd)
        # (external) edit command
        if xedit_match:
            filename = guess_filename(xedit_match.groups()[0])
            self.widget_proxy.edit(filename, external_editor=True)
        # local edit command
        elif edit_match:
            filename = guess_filename(edit_match.groups()[0])
            if osp.isfile(filename):
                self.widget_proxy.edit(filename)
            else:
                self.stderr_write.write(
                                "No such file or directory: %s\n" % filename)
        # remove reference (equivalent to MATLAB's clear command)
        elif clear_match:
            varnames = clear_match.groups()[0].replace(' ', '').split(',')
            for varname in varnames:
                try:
                    self.namespace.pop(varname)
                except KeyError:
                    pass
        # Execute command
        elif cmd.startswith('!'):
            # System ! command
            pipe = programs.run_shell_command(cmd[1:])
            txt_out = encoding.transcode( pipe.stdout.read().decode() )
            txt_err = encoding.transcode( pipe.stderr.read().decode().rstrip() )
            if txt_err:
                self.stderr_write.write(txt_err)
            if txt_out:
                self.stdout_write.write(txt_out)
            self.stdout_write.write('\n')
            self.more = False
        # -- End of Special commands type II
        else:
            # Command executed in the interpreter
#            self.widget_proxy.set_readonly(True)
            self.more = self.push(cmd)
#            self.widget_proxy.set_readonly(False)
        
        if new_prompt:
            self.widget_proxy.new_prompt(self.p2 if self.more else self.p1)
        if not self.more:
            self.resetbuffer()