Sublime Text 3配置Python交互环境
今天学Python时遇到如下代码:
#!/usr/bin/python3
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
guess = int(input("请输入你猜的数字:"))
if guess == number:
print("恭喜,你猜对了!")
elif guess < number:
print("猜的数字小了...")
elif guess > number:
print("猜的数字大了...")
⌘+b执行该段代码后我发现输入数字后,控制台无法进行下一步,无法建立互动,于是Google如何在ST3中建立Python交互环境。
在用ST3学习Python前,我就安装了以下三个据说是学Python必装的Package:
- SublimeCodeIntel
- SublimeLinter
- SublimeREPL
其中SublimeREPL就可以搭建起Python交互环境。
修改SublimeREPL
选择Tools
-SublimeREPL
-Python
-Python-RUN current file
,就可以建立起上述代码的交互环境。当我点击了Python-RUN current file
ST3又报错,一看还是编码问题,看来还得像上一篇文章一样调整一下SublimeREPL的Python编码。在/Users/你的用户名/Library/Application Support/Sublime Text 3/Packages/SublimeREPL/config/Python
或者Preferences-Browse Packages...-SublimeREPL-config-Python
路径中找到Main.sublime-menu
这个文件打开,定位到caption": "Python - RUN current file"
那块,原始代码为:
{"command": "repl_open",
"caption": "Python - RUN current file",
"id": "repl_python_run",
"mnemonic": "R",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python", "-u", "$file_basename"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "python",
"extend_env": {"PYTHONIOENCODING": "utf-8"}
}
},
我改成下面这样:
{"command": "repl_open",
"caption": "Python - RUN current file",
"id": "repl_python_run",
"mnemonic": "R",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python3", "-u", "-i", "$file_basename"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "python",
"extend_env": {"PYTHONIOENCODING": "utf-8"}
}
},
这样就解决了RUN current file
时的编码问题。但这样还有一个问题,每次需要交互,必须要点击菜单栏Tools然后一层层点进去才能跑代码,还需要设置一个快捷键。
设置快捷键
在Preferences-Key Bindings
进行快捷键设置。在显示的文件名为Default (OSX).sublime-keymap - User
文档的两个方括号间粘贴如下代码:
{ "keys": ["ctrl+r"],
"command": "repl_open",
"caption": "Python - RUN current file",
"mnemonic": "R",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python3", "-u", "-i", "$file_basename"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "python",
"extend_env": {"PYTHONIOENCODING": "utf-8"}
}
}
我设置了ctrl+r
为RUN current file
的快捷键。
到这里,Python在ST3的交互问题就全部搞定了,并且有了一个快捷键可以快速方便的执行交互类型的代码了。