美文网首页
9. Mac下sublime text3配置sublimeREP

9. Mac下sublime text3配置sublimeREP

作者: MiracleJQ | 来源:发表于2019-04-13 01:20 被阅读0次

一、安装

SublimeREPL是ST中的一个插件,它可以让我们在ST中运行解释器(REPL),而且对Python还有特别的支持,能运行选中的代码并且启动PDB调试。

我们可以使用Package Control来安装这个,在ST3中使用快捷键Ctrl+Shift+P,调出Package Control界面,不想用快捷键的可以在Preferences->Package Control中调出。在输入框输入Install Package。

image.png

SublimeREPL,然后回车安装即可。但是有时候会出现找不到这个库的情况。这个时候可以去SublimeREPL的github上面下载源码,然后解压到ST3的包目录(./User/AppData/Roaming/Sublime Text 3/Package)中。

二、使用

安装好了之后,可以在ST3中Tools->SublimeREPL->Python看到一些Python的启动选项,可以点开其中的Python,这个会调用系统中的Python解释器,并在ST3中呈现。也可以写一两个Python程序试一下其他的功能,里面有RUN current file,PDB current file等等。这样我们就可以在ST3中编写Python,并且可以直接调试。

但是,每次都要点击这么多按钮,确实比较麻烦,我们来设置几个快捷键,让整个操作便捷一点。进入快捷键绑定界面,Preferences->Key Bindings调出ST3的快捷键绑定界面。在User那个文件中加入下面这些代码。

[
  {
    "keys":["f4"],
    "caption": "SublimeREPL: Python",
    "command": "run_existing_window_command",
    "args": {
      "id": "repl_python_ipython",
      "file": "config/Python/Main.sublime-menu"
    }
  },
  {
    "keys": [
      "f5"
    ],
    "caption": "SublimeREPL: Python - RUN current file",
    "command": "run_existing_window_command",
    "args": {
      "id": "repl_python_run",
      "file": "config/Python/Main.sublime-menu"
    }
  },
  {
    "keys": [
      "f8"
    ],
    "caption": "SublimeREPL: Python - PDB current file",
    "command": "run_existing_window_command",
    "args":
    {
        "id": "repl_python_pdb",
        "file": "config/Python/Main.sublime-menu"
    }
  }
]

F4是调出python环境, F5是运行当前文件, F8是单步调试

修改默认python环境, (改为conda虚拟环境)

在网上找了诸多教程, 均不能实现, 最后自己摸索直接改了代码中命令, 将sublime的默认python环境直接改为conda的虚拟环境.

python run current file为例, 进行更改

  • open Sublime and select Preferences → Browse Packages… to open your Packages folder in your operating system's file browser application (Finder, Windows Explorer, Nautilus, etc.). Open the SublimeREPL folder, then config, then Python

cmd处的python替换成你想要使用的python环境, 如我直接替换成了我的虚拟环境

image.png

接下来结合上面进行的快捷键, 按下F5之后就会默认用conda 虚拟环境来执行当前文件了

其他的也是同样的修改方式

sublime text3修改ipython默认环境

为什么这里把ipython单独拿出来, 因为sublime text3的ipython环境如果还是直接像上面那样更改, 运行时会报错, 原因是With the release of IPython 4.0, the structure has completely changed, and is now implemented as a kernel for the Jupyter core

  • 执行环境还是按照上述更改python默认运行环境的方式, 进行更改

  • 修改ipy_repl.py文件:

    1. Use pip to install IPython 4 and Jupyter (the -U flag means "upgrade"):
pip install -U ipython==4.1.1 jupyter_console==4.1.0 jupyter

This will install the latest working versions of IPython and Jupyter (see note below), along with a bunch of related modules. I've tested this on several systems so far (Ubuntu various versions, OS X 10.10.5, Windows 8.1 Enterprise, and Windows 7 Professional) and none required a compiler for building any of the required packages, but I did have a lot of the prerequisites installed already. If you're running Windows and you get a message complaining about not being able to find a compiler, check out Christoph Gohlke's Python Extension Packages for Windows repository and you should be able to find a .whl file that can be installed with pip.

  1. In Sublime (versions 2 and 3), select Preferences → Browse Packages… to open up the Packages folder in your operating system's file manager utility (Windows Explorer, Finder, Nautilus, etc.) Navigate to Packages/SublimeREPL/config/Python and open ipy_repl.py in Sublime. 将文件内容替换为以下代码(代码有点多, 我都贴出来了):
import os
import sys
import json
import socket
import threading

activate_this = os.environ.get("SUBLIMEREPL_ACTIVATE_THIS", None)

# turn off pager
os.environ['TERM'] = 'emacs'

if activate_this:
    with open(activate_this, "r") as f:
        exec(f.read(), {"__file__": activate_this})

try:
    import IPython
    IPYTHON = True
    version = IPython.version_info[0]
except ImportError:
    IPYTHON = False

if not IPYTHON:
    # for virtualenvs w/o IPython
    import code
    code.InteractiveConsole().interact()

# IPython 4
if version > 3:
    from traitlets.config.loader import Config
# all other versions
else:
    from IPython.config.loader import Config

editor = "subl -w"

cfg = Config()
cfg.InteractiveShell.readline_use = False
cfg.InteractiveShell.autoindent = False
cfg.InteractiveShell.colors = "NoColor"
cfg.InteractiveShell.editor = os.environ.get("SUBLIMEREPL_EDITOR", editor)

# IPython 4.0.0
if version > 3:
    try:
        from jupyter_console.app import ZMQTerminalIPythonApp

        def kernel_client(zmq_shell):
            return zmq_shell.kernel_client
    except ImportError:
        raise ImportError("jupyter_console required for IPython 4")
# IPython 2-3
elif version > 1:
    from IPython.terminal.console.app import ZMQTerminalIPythonApp

    def kernel_client(zmq_shell):
        return zmq_shell.kernel_client
else:
    # Ipython 1.0
    from IPython.frontend.terminal.console.app import ZMQTerminalIPythonApp

    def kernel_client(zmq_shell):
        return zmq_shell.kernel_manager

embedded_shell = ZMQTerminalIPythonApp(config=cfg, user_ns={})
embedded_shell.initialize()

if os.name == "nt":
    # OMG what a fugly hack
    import IPython.utils.io as io
    io.stdout = io.IOStream(sys.__stdout__, fallback=io.devnull)
    io.stderr = io.IOStream(sys.__stderr__, fallback=io.devnull)
    embedded_shell.shell.show_banner()  # ... my eyes, oh my eyes..

ac_port = int(os.environ.get("SUBLIMEREPL_AC_PORT", "0"))
ac_ip = os.environ.get("SUBLIMEREPL_AC_IP", "127.0.0.1")
if ac_port:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ac_ip, ac_port))

def read_netstring(s):
    size = 0
    while True:
        ch = s.recv(1)
        if ch == b':':
            break
        size = size * 10 + int(ch)
    msg = b""
    while size != 0:
        msg += s.recv(size)
        size -= len(msg)
    ch = s.recv(1)
    assert ch == b','
    return msg

def send_netstring(sock, msg):
    payload = b"".join([str(len(msg)).encode("ascii"), b':', msg.encode("utf-8"), b','])
    sock.sendall(payload)

def complete(zmq_shell, req):
    kc = kernel_client(zmq_shell)
    # Ipython 4
    if version > 3:
        msg_id = kc.complete(req['line'], req['cursor_pos'])
    # Ipython 1-3
    else:
        msg_id = kc.shell_channel.complete(**req)
    msg = kc.shell_channel.get_msg(timeout=50)
    # end new stuff
    if msg['parent_header']['msg_id'] == msg_id:
        return msg["content"]["matches"]
    return []

def handle():
    while True:
        msg = read_netstring(s).decode("utf-8")
        try:
            req = json.loads(msg)
            completions = complete(embedded_shell, req)
            result = (req["text"], completions)
            res = json.dumps(result)
            send_netstring(s, res)
        except Exception:
            send_netstring(s, b"[]")

if ac_port:
    t = threading.Thread(target=handle)
    t.start()

embedded_shell.start()

if ac_port:
    s.close()

好, 这样按下F4就会直接调出ipython的

相关文章

网友评论

      本文标题:9. Mac下sublime text3配置sublimeREP

      本文链接:https://www.haomeiwen.com/subject/zbpkwqtx.html