How can I use venv with SublimeREPL in Sublime Text 3? - python

For starters, here is my dev environment:
Windows 7 (although I have the same issue on another machine that is Windows 10)
Python 3.6
Git Bash
Sublime Text 3 (version 3.1.1, Build 3176)
SublimeREPL
In Git Bash, I created a new virtual environment:
$ mkdir ~/.venv
$ cd ~/.venv
$ python -m venv test-env
To activate that virtual environment, I use:
$ source ~/.venv/test-env/Scripts/activate
NOTE: I had to modify the activate script (NOT activate.bat) to get the venv to activate properly. Specifically, I changed line 40 which looked something like:
VIRTUAL_ENV="C:\Users\my_user_name\.venv\test-env"
to
VIRTUAL_ENV="/c/Users/my_user_name/.venv/test-env"
Now, when I am in the test-env virtual environment (as evidenced by the "(test-env)" text in Git Bash), I can do the usual stuff like
(test-env)
$ pip install numpy
I also have the SublimeREPL package installed in Sublime Text 3. I setup a new build system (SublimeREPL-python.sublime-build) that looks like:
{
"target": "run_existing_window_command",
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
Now, suppose I have a script
# test.py
import numpy as np
print('numpy was imported without error')
I can type Ctrl+Shift+B, then start typing 'repl', which autoselects the SublimeREPL-python build, then hit Enter. The SublimeREPL appears, but generates an error:
Traceback (most recent call last):
File "test.py", line 2, in <module>
import numpy as numpy
ModuleNotFoundError: No module named 'numpy'
>>>
SublimeREPL was called without using my virtual environment, which causes it to throw the error because numpy wasn't installed in my global python environment.
How can I run my Python script from Sublime Text 3 using SublimeREPL and accessing my virtual environment that was created using venv?
FWIW, I already tried creating a Sublime Project for this code and adding the following to the .sublime-project file:
"build_systems":
[
{
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"name": "test-env",
"selector": "source.python",
"shell_cmd": "\"C:\\Users\\my_user_name\\.venv\\test-env\\Scripts\\python\" -u \"$file\""
}
]
This allowed me to type Ctrl+Shift+B, then "test-env", then Enter (to build with the test-env build system I just created), which worked as expected and ran without error. However, it does not use SublimeREPL, which I'd like so that I can debug my code (which is more complicated that the simple test script I posted above!) and explore the variables in the REPL rather than just running code in the console.

I know it's not an answer, but a partial solution that might help anyone else on same situation as I am. Also because SublimeREPL support is almost nothing.
Note: This solution requires to modify Main.sublime-menu for every environment and assumes SublimeREPL runs interactively already (adding the "-i" for execution).
Browse packages and open SublimeREPL/config/python/Main-sublime-menu.
Search for line with "id": "repl_python_run".
Duplicate the nearest content inside the curly brackes.
Basically pasting after the same end bracket the following (note the "-i" option on "cmd" to run interactively):
{"command": "repl_open",
"caption": "Python - RUN current file",
"id": "repl_python_run",
"mnemonic": "R",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python", "-u", "-i", "$file_basename"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "python",
"extend_env": {"PYTHONIOENCODING": "utf-8"}
}
},
Change the id repl_python_run to whatever you like, e.g., repl_my_first_env_python.
Change python commmand from "cmd": ["python", "-u", "-i", "$file_basename"] to use wherever your python's virtual environment executable is, e.g., /home/me/.virtualenvs/my_first_env/bin/python (linux example). Save the file.
Edit project to include inside the square brackets from "build_systems" the following:
(If you have no project, create a new Build System and paste next block of code)
{
"name": "my first env",
"target": "run_existing_window_command",
"id": "repl_my_first_env_python",
"file": "config/Python/Main.sublime-menu"
},
Finally Save.
You'll see when Ctrl+Shift+B you'll see my first env as an option.

Related

Running pygame in Sublime Text 3 [duplicate]

I'm trying to get Sublime Text 3 to run a Python script. A simple two liner
var = raw_input("Enter something: ")
print("You entered " + var)
which asks for input, waits for it, then prints it out in windows console prompt.
Seeing the number of similar questions on the site, this is a problem for quite a number of users, so I went through those and tried ... stuff. Made a copy of exec.py file, commented that one line, made a new pythonw build file, tried messing about with the build file ... nothing seems to work.
In lack of a definite solution, how do you work with input using Sublime Text?
Sublime Text on its own cannot handle input via raw_input() (Python 2) or input() (Python 3). The same is true of other languages as well - Ruby's gets, Java's Scanner class, Node's readline class, scanf in C, cin in C++, etc. One short-term solution is to get Package Control if you don't already have it, then install SublimeREPL. It allows you to transfer or run part or all of your code through the running REPL. It may require some configuration of the Main.sublime-menu files to get your preferred interpreter to run properly. Alternatively, you can use the excellent Terminus plugin - details are at the bottom.
If the code you're running doesn't play well with SublimeREPL (for instance, you're using C/C++/Java/etc. and need to compile code before it runs), or you just want to run it independently of Sublime, you'll need to make your own build system. Save the following as Packages/User/Python_cmd.sublime-build:
Windows
{
"cmd": ["start", "cmd", "/k", "c:/python38/python.exe", "$file"],
"selector": "source.python",
"shell": true,
"working_dir": "$file_dir",
"env": {"PYTHONIOENCODING": "utf-8"}
}
changing the path to your Python executable as appropriate. Then, go to Tools -> Build System and select Python_cmd, and when you hit CtrlB to build, a new cmd window will open up with your file running. The /k option returns to the command prompt, without closing the window, after your program is done running so you can examine output, tracebacks, etc.
Please note that this build system is Windows-specific, as macOS and Linux do not have cmd. Build systems for those platforms are below.
macOS
If you are running OS X/macOS, the following build system will open your program in a new instance of Terminal. Save it as Packages/User/Python_Terminal.sublime-build. In my testing on macOS 10.15, the Terminal window didn't always come to the top when activated, so if you may need to look for it behind other windows.
{
"shell_cmd": "osascript -e 'tell app \"Terminal\" to do script \"cd $file_path && python3 -u $file\"'",
"working_dir": "$file_path",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"}
}
You may need to specify the path to your Python executable if it's not on your $PATH.
Linux
And finally, here is a build system for Linux. It was tested on Ubuntu, so if you use another distribution you'll need to ensure that gnome-terminal is installed. Save it as Packages/User/Python_shell.sublime-build. Once the program has finished running, hit any key to close the window.
{
"shell_cmd": "gnome-terminal --working-directory=$file_path -- bash -c 'python3 -u \"$file\" && read -n 1 -s -r'",
"working_dir": "$file_path",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"}
}
For reference, the Packages directory is the one opened when selecting Preferences → Browse Packages…:
Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages
OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages
Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages
Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages InstallationFolder\Sublime Text\Data\Packages
The exact path depends on version and whether or not you upgraded from Sublime Text 3.
I have only tested these build systems with Python, but they should work fine for any language. When modifying, just make sure that all the single and double quotes match up – you'll get errors or unexpected behavior if they don't.
UPDATE
There is a platform-independent plugin called Terminus that, among other things, provides a drop-in replacement for the default exec build system engine. It allows you to interact with your program in the build panel below your code. Once you've installed it from Package Control, create the following build system (again, for Python):
{
"target": "terminus_exec",
"cancel": "terminus_cancel_build",
"cmd": [
"/path/to/python", "-u", "$file"
],
"working_dir": "$file_path",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
}
You'll need to adjust the path to your Python executable, as above. Make sure you read the documentation to find out all the other ways you can make use of this great plugin.
To add on to the answer from Shritam Kumar Mund, to make a key binding for this:
{ "keys": ["alt+k", "alt+k"], "command": "repl_open", "args": {"cmd":
["python", "-u", "$file_basename"], "cwd": "$file_path", "encoding":
"utf8", "extend_env": {"PYTHONIOENCODING": "utf-8"}, "external_id":
"python", "syntax": "Packages/Python/Python.tmLanguage", "type":
"subprocess"}},
I found this by using the following in the console:
sublime.log_commands(True)
Sublime Text does not support inputting data into a program. For working with inputs you need to install a package called SublimeREPL.
Follow this:
open Sublime Text >> CTRL + P
CTRL + P will open the Package control
Click on Package Control: Install package
Wait for a sec to pop up a search bar.
Type SublimeREPL and Click it.
It'll get installed in a few secs.
Then follow the following steps to run your program;
Tools >> SublimeREPL >> Python >> Python run Current File
It'll open a new window, where you can give your input and get the output.
You can use this sublime_build file which make run on cmd when you press ctrl+B .
Just go to tool ->sublime build->new build system and paste the below given as it is;
I have personally edited this sublime build file with my experience and believe me it has some good functionalities:
color changing when program terminates or ends
interactive output and input
console window automatic opening
pause after program finishes and wait till enter
{
"cmd":["start", "cmd", "/c" ,"python $file && color b0 && pause"],
"selector": "source.python",
"working_dir": "${file_path}",
"file_regex": "(.+):(\\d+): error: ",
"shell": true
}
Thanks #MattDMo for the answer, which doesn't require installing any plugin. But after I tried the command in macOS:
"shell_cmd": "osascript -e 'tell app \"Terminal\" to do script \"cd $file_path && python3 -u $file\"'",
I find it seems to run from background every time, which is not convenient.
So I tried another method: to use a temp.sh to run. Here is the command:
"cmd": ["zsh", "-c", "echo \"python3 ${file}\" > /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; sleep 2 ;rm /tmp/tmp.sh"],
This method will pop up a new window to the front, and it should be feasible on other platforms after a small modification, but I didn't try.
here is the full content in "python_input.sublime-build":
{
"cmd": ["zsh", "-c", "echo \"python3 ${file}\" > /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; sleep 2 ;rm /tmp/tmp.sh"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"},
}

How to add additional shell command in VS code task build?

Environment:
Windows 10 x64
VSCode Version 1.23.1
python 3.6.4
I've been trying to switch from sublime text 3 to VS code.
I have python 3.6.4 installed in my computer, all set with the PATH and other stuff.
In my sublime text 3, I set the build for python 3 (*.sublime-build) as:
{
"shell_cmd": "python --version && echo. && python -u \"$file\"",
"cmd": ["C:/Users/jxie0/AppData/Local/Programs/Python/Python36/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9])*",
"selector": "source.python"
}
this will add a python version output with a blank line, before running the python code, take print('hello world') as an example:
Python 3.6.4
hello world
[Finished in 0.1s]
And sublime automatic add a timer for the code at the end.
In my current task.json for VS code, I have:
{
"version": "0.1.0",
"command": "python",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}
This will work, but just simply show the output of the python codes:
hello world
Is there anyway I can tune it into something that can give me same kind of output style as I got from sublime text? If the timer is not possible, at least can I add a shell command as a header to show the python 3 version?
Additional question: what does that "version": "0.1.0", do in VS code? Which version does it refer to?
Thanks!
You can use the same command as you were using before, the difference is in how the file to be passed is referenced. In vscode the equivalent would be
python --version && echo && python -u ${file}
This command can be broken up into three commmands, the first, python --version, prints the python version. The second, echo, prints the empty line. The third, python -u ${file}, actually runs the python script.
As for the timer, I don't know of a way to make that occur in vscode but it would not be too difficult to implement this in the script itself, such as in Measure time elapsed in Python?
A simple configuration for this task could be as follows:
{
"version": "2.0.0",
"tasks": [
{
"label": "python",
"type": "shell",
"command": "python --version && echo && python -u ${file}",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
}
}
]
}
Note that this assumes you have python on your path, otherwise you will have to specify the path to python.exe when the python command is used in command.

How do I run python 3.5 in Sublime Text 3

I have installed the python 3.5 interpretor in my device (Windows).
Can anybody guide me through the process of using packages to run it like SublimeREPL?
Yes, you can use any Python version you want to run programs from Sublime - you just need to define a new build system. Select Tools -> Build System -> New Build System, then delete its contents and replace it with:
{
"cmd": ["C:/Python35/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
assuming that C:/Python35/python.exe is the correct path. If python.exe resides someplace else, just put in the correct path, using forward slashes / instead of the Windows standard backward slashes \.
Save the file as Packages/User/Python3.sublime-build, where Packages is the folder opened by selecting Preferences -> Browse Packages... - Sublime should already automatically save it in the right directory. Now, there will be a Tools -> Build System -> Python3 option that you can select for running files with Python 3.
For details on setting up SublimeREPL with Python 3, please follow the instructions in my answer here.
if you have installed python3 and SublimeREPL, you can try setting up key bindings with the correct path to the python3 file.
[
{
"keys":["super+ctrl+r"],
"command": "repl_open",
"caption": "Python 3.6 - Open File",
"id": "repl_python",
"mnemonic": "p",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["The directory to your python3.6 file", "-i", "$file"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "python",
"extend_env": {"PYTHONIOENCODING": "utf-8"}
}
}
]
You can try by copying this code into your /Sublime Text 3/Preferences/Key Bindings/
Hope this helps!

Keybinding for SublimeREPL to launch a Python virtualenv

I am using Sublime Text 2 on a Mac. I have the SublimeREPL enabled and I am am trying to create a keybinding that that launches a REPL window for a virtual environment located in my virtualenvwrapper folder, ~/Documents/PythonEnvs/
I've tried modifying the code for my keybindings using
Running Python interactively from within Sublime Text 2
as a starting point, followed by
Sublime text3 and virtualenvs
and Running Python interactively from within Sublime Text 2
I'm probably missing something completely obvious, but it's actually less and less clear to me now if I need to be writing a plugin, a macro, or (what I thought) just writing a simple key binding to launch the SublimeREPL for Python using a virtual environment.
Has anyone written a keybinding to launch Python in a virtualenv? If so, how did you go about doing it?
The following is in my keybindings file.... it launches a new window that immediately reports "REPL CLOSED." The code doesn't work, or even come close... the best I've managed to do is get it to launch a current Python file in the Python env that comes with Sublime.... but in the interest of showing what I've tried, I've tried modifying my user's sublime-keymap file (latest iteration of that modifying below) for about an hour and a half now... and I can't anything online related to launching a SublimeREPL window in a a VirtualEnv, or anything similar enough that I can figure out how to solve this problem. At this point I gotta throw in the towel and see if anyone else has managed to do it. Thank you in advance for your help, if you have any ideas.
[
{ "keys": ["command+shift+p"], "command": "repl_open",
"caption": "Python - virtualenv",
"mnemonic": "p",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python", "-u", "$file"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "Python - virtualenv"
}
}
]
This should work:
[
{
"keys": ["command+shift+p"],
"command": "repl_open",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python", "-i", "-u"],
"cwd": "$file_path",
"syntax": "Packages/Python/Python.tmLanguage",
"external_id": "python",
"extend_env": {"PYTHONIOENCODING": "utf-8"}
}
}
]
To get this, I simply checked what sublimeREPL used itself.
Use "args": on line 19 of ~/Library/Application Support/Sublime Text 2/Packages/SublimeREPL/config/Python/Main.sublime-menu for the args in Key Bindings -- User
Side note:
To switch from version 2.7 to 3, replace
"cmd": ["python", "-i", "-u"],
with
"cmd": ["python3", "-i", "-u"],

Can't send input to running program in Sublime Text

I'm trying to get Sublime Text 3 to run a Python script. A simple two liner
var = raw_input("Enter something: ")
print("You entered " + var)
which asks for input, waits for it, then prints it out in windows console prompt.
Seeing the number of similar questions on the site, this is a problem for quite a number of users, so I went through those and tried ... stuff. Made a copy of exec.py file, commented that one line, made a new pythonw build file, tried messing about with the build file ... nothing seems to work.
In lack of a definite solution, how do you work with input using Sublime Text?
Sublime Text on its own cannot handle input via raw_input() (Python 2) or input() (Python 3). The same is true of other languages as well - Ruby's gets, Java's Scanner class, Node's readline class, scanf in C, cin in C++, etc. One short-term solution is to get Package Control if you don't already have it, then install SublimeREPL. It allows you to transfer or run part or all of your code through the running REPL. It may require some configuration of the Main.sublime-menu files to get your preferred interpreter to run properly. Alternatively, you can use the excellent Terminus plugin - details are at the bottom.
If the code you're running doesn't play well with SublimeREPL (for instance, you're using C/C++/Java/etc. and need to compile code before it runs), or you just want to run it independently of Sublime, you'll need to make your own build system. Save the following as Packages/User/Python_cmd.sublime-build:
Windows
{
"cmd": ["start", "cmd", "/k", "c:/python38/python.exe", "$file"],
"selector": "source.python",
"shell": true,
"working_dir": "$file_dir",
"env": {"PYTHONIOENCODING": "utf-8"}
}
changing the path to your Python executable as appropriate. Then, go to Tools -> Build System and select Python_cmd, and when you hit CtrlB to build, a new cmd window will open up with your file running. The /k option returns to the command prompt, without closing the window, after your program is done running so you can examine output, tracebacks, etc.
Please note that this build system is Windows-specific, as macOS and Linux do not have cmd. Build systems for those platforms are below.
macOS
If you are running OS X/macOS, the following build system will open your program in a new instance of Terminal. Save it as Packages/User/Python_Terminal.sublime-build. In my testing on macOS 10.15, the Terminal window didn't always come to the top when activated, so if you may need to look for it behind other windows.
{
"shell_cmd": "osascript -e 'tell app \"Terminal\" to do script \"cd $file_path && python3 -u $file\"'",
"working_dir": "$file_path",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"}
}
You may need to specify the path to your Python executable if it's not on your $PATH.
Linux
And finally, here is a build system for Linux. It was tested on Ubuntu, so if you use another distribution you'll need to ensure that gnome-terminal is installed. Save it as Packages/User/Python_shell.sublime-build. Once the program has finished running, hit any key to close the window.
{
"shell_cmd": "gnome-terminal --working-directory=$file_path -- bash -c 'python3 -u \"$file\" && read -n 1 -s -r'",
"working_dir": "$file_path",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"}
}
For reference, the Packages directory is the one opened when selecting Preferences → Browse Packages…:
Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages
OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages
Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages
Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages InstallationFolder\Sublime Text\Data\Packages
The exact path depends on version and whether or not you upgraded from Sublime Text 3.
I have only tested these build systems with Python, but they should work fine for any language. When modifying, just make sure that all the single and double quotes match up – you'll get errors or unexpected behavior if they don't.
UPDATE
There is a platform-independent plugin called Terminus that, among other things, provides a drop-in replacement for the default exec build system engine. It allows you to interact with your program in the build panel below your code. Once you've installed it from Package Control, create the following build system (again, for Python):
{
"target": "terminus_exec",
"cancel": "terminus_cancel_build",
"cmd": [
"/path/to/python", "-u", "$file"
],
"working_dir": "$file_path",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
}
You'll need to adjust the path to your Python executable, as above. Make sure you read the documentation to find out all the other ways you can make use of this great plugin.
To add on to the answer from Shritam Kumar Mund, to make a key binding for this:
{ "keys": ["alt+k", "alt+k"], "command": "repl_open", "args": {"cmd":
["python", "-u", "$file_basename"], "cwd": "$file_path", "encoding":
"utf8", "extend_env": {"PYTHONIOENCODING": "utf-8"}, "external_id":
"python", "syntax": "Packages/Python/Python.tmLanguage", "type":
"subprocess"}},
I found this by using the following in the console:
sublime.log_commands(True)
Sublime Text does not support inputting data into a program. For working with inputs you need to install a package called SublimeREPL.
Follow this:
open Sublime Text >> CTRL + P
CTRL + P will open the Package control
Click on Package Control: Install package
Wait for a sec to pop up a search bar.
Type SublimeREPL and Click it.
It'll get installed in a few secs.
Then follow the following steps to run your program;
Tools >> SublimeREPL >> Python >> Python run Current File
It'll open a new window, where you can give your input and get the output.
You can use this sublime_build file which make run on cmd when you press ctrl+B .
Just go to tool ->sublime build->new build system and paste the below given as it is;
I have personally edited this sublime build file with my experience and believe me it has some good functionalities:
color changing when program terminates or ends
interactive output and input
console window automatic opening
pause after program finishes and wait till enter
{
"cmd":["start", "cmd", "/c" ,"python $file && color b0 && pause"],
"selector": "source.python",
"working_dir": "${file_path}",
"file_regex": "(.+):(\\d+): error: ",
"shell": true
}
Thanks #MattDMo for the answer, which doesn't require installing any plugin. But after I tried the command in macOS:
"shell_cmd": "osascript -e 'tell app \"Terminal\" to do script \"cd $file_path && python3 -u $file\"'",
I find it seems to run from background every time, which is not convenient.
So I tried another method: to use a temp.sh to run. Here is the command:
"cmd": ["zsh", "-c", "echo \"python3 ${file}\" > /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; sleep 2 ;rm /tmp/tmp.sh"],
This method will pop up a new window to the front, and it should be feasible on other platforms after a small modification, but I didn't try.
here is the full content in "python_input.sublime-build":
{
"cmd": ["zsh", "-c", "echo \"python3 ${file}\" > /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; sleep 2 ;rm /tmp/tmp.sh"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"},
}

Categories

Resources