Python 崇高的 text3 和 virtualenvs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24963030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:31:57  来源:igfitidea点击:

Sublime text3 and virtualenvs

pythonsublimetext3virtualenvwrapper

提问by Doc

I'm totally new with sublime3, but i couldn't find anything helpful for my problem...

我对 sublime3 完全陌生,但我找不到任何对我的问题有帮助的东西......

I've differents virtualenvs (made with virtualenwrapper) and I'd like to be able to specify which venv to use with each project

我有不同的 virtualenvs(用 virtualenwrapper 制作),我希望能够指定每个项目使用哪个 venv

Since I'm using SublimeREPL plugin to have custom builds, how can i specify which python installation to build my project with?

由于我使用 SublimeREPL 插件进行自定义构建,我如何指定使用哪个 python 安装来构建我的项目?

for example, when i work on project A i want to run scripts with venvA's python, and when i work on project B i want to run things with venvB (using a different build script)

例如,当我在项目 A 上工作时,我想用 venvA 的 python 运行脚本,当我在项目 B 上工作时,我想用 venvB 运行(使用不同的构建脚本)

sorry my terrible english...

对不起我糟糕的英语...

采纳答案by Soytoise

Hopefully this is along the lines you are imagining. I attempted to simplify my solution and remove some things you likely do not need.

希望这符合您的想象。我试图简化我的解决方案并删除一些您可能不需要的东西。

The advantages of this method are:

这种方法的优点是:

  • Single button press to launch a SublimeREPL with correct interpreter andrun a file in it if desired.
  • After setting the interpreter, no changes or extra steps are necessary when switching between projects.
  • Can be easily extended to automatically pick up project specific environment variables, desired working directories, run tests, open a Django shell, etc.
  • 按下单个按钮以启动带有正确解释器的 SublimeREPL,在需要时在其中运行文件。
  • 设置解释器后,在项目之间切换时无需更改或额外步骤。
  • 可以轻松扩展以自动获取项目特定的环境变量、所需的工作目录、运行测试、打开 Django shell 等。

Let me know if you have any questions, or if I totally missed the mark on what you're looking to do.

如果您有任何问题,或者我完全没有注意到您想要做的事情,请告诉我。

Set Project's Python Interpreter

设置项目的 Python 解释器

  1. Open our project file for editing:

    Project -> Edit Project
    
  2. Add a new key to the project's settings that points to the desired virtualenv:

    "settings": {
        "python_interpreter": "/home/user/.virtualenvs/example/bin/python"
    }
    
  1. 打开我们的项目文件进行编辑:

    Project -> Edit Project
    
  2. 向项目设置中添加一个指向所需 virtualenv 的新键:

    "settings": {
        "python_interpreter": "/home/user/.virtualenvs/example/bin/python"
    }
    

A "python_interpreter"project settings key is also used by plugins like Anaconda.

一个"python_interpreter"项目设置键也被类似的插件蟒蛇

Create plugin to grab this setting and launch a SublimeREPL

创建插件以获取此设置并启动 SublimeREPL

  1. Browse to Sublime Text's Packagesdirectory:

    Preferences -> Browse Packages...
    
  2. Create a new python file for our plugin, something like: project_venv_repls.py

  3. Copy the following python code into this new file:

    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'
                }
            )
    
  1. 浏览到 Sublime Text 的Packages目录:

    Preferences -> Browse Packages...
    
  2. 为我们的插件创建一个新的 python 文件,例如: project_venv_repls.py

  3. 将以下 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'
                }
            )
    

Set Hotkeys

设置热键

  1. Open user keybind file:

    Preferences -> Key Bindings - User
    
  2. Add a few keybinds to make use of the plugin. Some examples:

    // 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"
        }
    }
    
  1. 打开用户密钥绑定文件:

    Preferences -> Key Bindings - User
    
  2. 添加一些键绑定以使用插件。一些例子:

    // 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"
        }
    }
    

回答by Allison

You're looking for custom build systems.

您正在寻找自定义构建系统。

From the menu bar, click Tools -> Build Systems -> New Build System...

从菜单栏中,单击 Tools -> Build Systems -> New Build System...

Fill out the template it gives and save it under any filename ending in .sublime-buildto your Userfolder.

填写它提供的模板并将其保存在.sublime-build以您的User文件夹结尾的任何文件名下。

Here is the documentation for making custom build systems:

以下是制作自定义构建系统的文档:

http://docs.sublimetext.info/en/latest/reference/build_systems.html

http://docs.sublimetext.info/en/latest/reference/build_systems.html

I recommend making a custom build system for python scripts, then add variants for each virtual env you want. (see variants http://docs.sublimetext.info/en/latest/reference/build_systems.html#variants)

我建议为 python 脚本制作一个自定义构建系统,然后为您想要的每个虚拟环境添加变体。(参见变体http://docs.sublimetext.info/en/latest/reference/build_systems.html#variants

One you make a build system, you can switch them from

您制作了一个构建系统,您可以从中切换它们

Tools -> Build Systems

(if not auto detected) and use the Command Palette (default ctrl + shift p) to switch between variants.

(如果没有自动检测到)并使用命令面板(默认 ctrl + shift p)在变体之间切换。

The only "gotcha" is the "cmd"parameter to describe what command to run. By default it takes an array of strings to run as a command, but you can use "shell_cmd"instead to just use a string of how you would run it via command line.

唯一的“问题”是"cmd"描述要运行的命令的参数。默认情况下,它需要一个字符串数组作为命令运行,但您可以"shell_cmd"使用一个字符串来代替通过命令行运行它的方式。

回答by Jay Wong

There is a sublime text3 package, named Virtualenv, allowing you to build using the Python from your virtualenv.

有一个名为 的 sublime text3 包,Virtualenv允许您使用 virtualenv 中的 Python 进行构建。

It supports any versions of Python in your virtualenv, and works very well for me (MacOS).

它支持您的 virtualenv 中的任何版本的 Python,并且对我(MacOS)非常有效。

To install it, we just command+Shift+Pto call out pacakge control (install it if you don't have it yet), then type install. Next type virtualenv, when you see it appears click returnto install it.

要安装它,我们只是command+ Shift+P调出pacakge控制(安装它,如果你没有的话还没有),然后键入install。Next type virtualenv,当你看到它出现时点击return安装它。

After installing it, select Tools--> Build System--> Python + Virtualenv. Then you can use command+ Bto execute your Python projects.

安装后,选择Tools--> Build System--> Python + Virtualenv。然后你可以使用command+B来执行你的 Python 项目。

Click Hereto check further information.

单击此处查看更多信息。

回答by Guohua Cheng

I have an alternative. Just creating a new 'Build System' which runs as if in the virtual environment. Here we call it 'my_python'. The aim is to use this build system to run my script directly without leaving sublime. You need to:

我有一个替代方案。只需创建一个新的“构建系统”,就像在虚拟环境中一样运行。这里我们称它为“my_python”。目的是使用这个构建系统直接运行我的脚本而不离开 sublime。你需要:

  1. First, preferences->Browse Packages. This will open a folder under which lies setting files. Go inside dir Userand create a new file named my_python.sublime-build(composed of the build system name followed by .sublime_build. After doing this, go to Tools -> Build Systemand you will see a new option my_python.
  2. Add the following JSON settings to that file.

    {
        "shell_cmd": "/Users/Ted/bsd/vector/.v_venv/bin/python -u \"$file\"",
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python"
    }
    

    Inside shell_cmd, change /Users/Ted/bsd/vector/.v_venv/bin/pythonto the path of your python virtual environment.

  3. Then just use the short key to build your script.

  1. 首先,preferences->Browse Packages。这将打开一个文件夹,其中包含设置文件。进入 dirUser并创建一个名为my_python.sublime-build(由构建系统名称后跟.sublime_build.组成的新文件。执行此操作后,转到Tools -> Build System,您将看到一个新选项my_python
  2. 将以下 JSON 设置添加到该文件。

    {
        "shell_cmd": "/Users/Ted/bsd/vector/.v_venv/bin/python -u \"$file\"",
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python"
    }
    

    在里面shell_cmd,更改/Users/Ted/bsd/vector/.v_venv/bin/python为您的python 虚拟环境的路径。

  3. 然后只需使用快捷键来构建您的脚本。

When you want to change your virtual environment, just copy its path to the setting file and all done. Maybe the approach seems containing a lots of work, but it works well and convenient.

当您想更改虚拟环境时,只需将其路径复制到设置文件即可。也许这种方法看起来包含很多工作,但它运行良好且方便。