我有不同的 virtualenv
(使用 virtualenwrapper
制作),我希望能够指定与哪个 virtualenv
一起使用每个项目。
由于我使用 SublimeREPL
插件进行自定义构建,我如何指定使用哪个 python 安装来构建我的项目?
例如,当我处理项目 A 时,我想用 venvA 的 python 运行脚本,而当我处理项目 B 时,我想用 venvB 运行东西(使用不同的构建脚本)。
最佳答案
希望这符合您的想象。我试图简化我的解决方案并删除一些您可能不需要的东西。
这种方法的优点是:
- 单击单个按钮以启动带有正确解释器的 SublimeREPL并如果需要,在其中运行文件。
- 设置解释器后,在项目之间切换时无需进行任何更改或额外步骤。
- 可以轻松扩展以自动获取项目特定的环境变量、所需的工作目录、运行测试、打开 Django shell 等。
如果您有任何问题,或者我完全错过了您想要做什么的标记,请告诉我。
设置项目的 Python 解释器
打开我们的项目文件进行编辑:
Project -> Edit Project
在项目设置中添加一个指向所需虚拟环境的新键:
"settings": { "python_interpreter": "/home/user/.virtualenvs/example/bin/python" }
"python_interpreter"
项目设置键也被 Anaconda 等插件使用.
创建插件以获取此设置并启动 SublimeREPL
浏览到 Sublime Text 的
Packages
目录:Preferences -> Browse Packages...
为我们的插件创建一个新的 python 文件,例如:
project_venv_repls.py
将以下 python 代码复制到这个新文件中:
import sublime_plugin class ProjectVenvReplCommand(sublime_plugin.TextCommand): """ Starts a SublimeREPL, attempting to use project's specified python interpreter. """ def run(self, edit, open_file='$file'): """Called on project_venv_repl command""" cmd_list = [self.get_project_interpreter(), '-i', '-u'] if open_file: cmd_list.append(open_file) self.repl_open(cmd_list=cmd_list) def get_project_interpreter(self): """Return the project's specified python interpreter, if any""" settings = self.view.settings() return settings.get('python_interpreter', '/usr/bin/python') def repl_open(self, cmd_list): """Open a SublimeREPL using provided commands""" self.view.window().run_command( 'repl_open', { 'encoding': 'utf8', 'type': 'subprocess', 'cmd': cmd_list, 'cwd': '$file_path', 'syntax': 'Packages/Python/Python.tmLanguage' } )
设置热键
打开用户键绑定(bind)文件:
Preferences -> Key Bindings - User
添加一些键绑定(bind)以使用该插件。一些例子:
// Runs currently open file in repl
{
"keys": ["f5"],
"command": "project_venv_repl"
},
// Runs repl without any file
{
"keys": ["f6"],
"command": "project_venv_repl",
"args": {
"open_file": null
}
},
// Runs a specific file in repl, change main.py to desired file
{
"keys": ["f7"],
"command": "project_venv_repl",
"args": {
"open_file": "/home/user/example/main.py"
}
}
关于python - Sublime text3 和 virtualenvs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24963030/