9. Mac下sublime text3配置sublimeREPL交互

一、安裝

SublimeREPL是ST中的一個(gè)插件,它可以讓我們?cè)赟T中運(yùn)行解釋器(REPL),而且對(duì)Python還有特別的支持,能運(yùn)行選中的代碼并且啟動(dòng)PDB調(diào)試。

我們可以使用Package Control來安裝這個(gè),在ST3中使用快捷鍵Ctrl+Shift+P,調(diào)出Package Control界面,不想用快捷鍵的可以在Preferences->Package Control中調(diào)出。在輸入框輸入Install Package。

image.png

SublimeREPL,然后回車安裝即可。但是有時(shí)候會(huì)出現(xiàn)找不到這個(gè)庫的情況。這個(gè)時(shí)候可以去SublimeREPL的github上面下載源碼,然后解壓到ST3的包目錄(./User/AppData/Roaming/Sublime Text 3/Package)中。

二、使用

安裝好了之后,可以在ST3中Tools->SublimeREPL->Python看到一些Python的啟動(dòng)選項(xiàng),可以點(diǎn)開其中的Python,這個(gè)會(huì)調(diào)用系統(tǒng)中的Python解釋器,并在ST3中呈現(xiàn)。也可以寫一兩個(gè)Python程序試一下其他的功能,里面有RUN current file,PDB current file等等。這樣我們就可以在ST3中編寫Python,并且可以直接調(diào)試。

但是,每次都要點(diǎn)擊這么多按鈕,確實(shí)比較麻煩,我們來設(shè)置幾個(gè)快捷鍵,讓整個(gè)操作便捷一點(diǎn)。進(jìn)入快捷鍵綁定界面,Preferences->Key Bindings調(diào)出ST3的快捷鍵綁定界面。在User那個(gè)文件中加入下面這些代碼。

[
  {
    "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是調(diào)出python環(huán)境, F5是運(yùn)行當(dāng)前文件, F8是單步調(diào)試

修改默認(rèn)python環(huán)境, (改為conda虛擬環(huán)境)

在網(wǎng)上找了諸多教程, 均不能實(shí)現(xiàn), 最后自己摸索直接改了代碼中命令, 將sublime的默認(rèn)python環(huán)境直接改為conda的虛擬環(huán)境.

python run current file為例, 進(jìn)行更改

  • 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環(huán)境, 如我直接替換成了我的虛擬環(huán)境

image.png

接下來結(jié)合上面進(jìn)行的快捷鍵, 按下F5之后就會(huì)默認(rèn)用conda 虛擬環(huán)境來執(zhí)行當(dāng)前文件了

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

sublime text3修改ipython默認(rèn)環(huán)境

為什么這里把ipython單獨(dú)拿出來, 因?yàn)閟ublime text3的ipython環(huán)境如果還是直接像上面那樣更改, 運(yùn)行時(shí)會(huì)報(bào)錯(cuò), 原因是With the release of IPython 4.0, the structure has completely changed, and is now implemented as a kernel for the Jupyter core

  • 執(zhí)行環(huán)境還是按照上述更改python默認(rèn)運(yùn)行環(huán)境的方式, 進(jìn)行更改

  • 修改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. 將文件內(nèi)容替換為以下代碼(代碼有點(diǎn)多, 我都貼出來了):
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就會(huì)直接調(diào)出ipython的

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容