Sublime - Python3 not printing non utf-8 characters (Spanish) - python

I think it's sublime related rather than python, running this snippet:
x = "Buenos días"
print(x)
will print in terminal/command prompt but not in sublimes build results. Did already a little bit of research but couldn't find a working solution. Removing the í acute accent to a i works as expected.

Generally speaking problems like this are caused by some interplay between how Python determines behind the scenes the encoding that it should use when it's generating output and how Sublime is executing the Python interpreter.
In particular where it may correctly determine the correct encoding when run from a terminal, the Python interpreter may get confused and pick the wrong one when Sublime invokes it.
The PYTHONIOENCODING environment variable can be used to tell the interpreter to use a specific encoding in favor of whatever it might have otherwise automatically selected.
The sublime-build file lets you specify custom environment variables to apply during a build using the env key, so you can do something like the following:
{
"shell_cmd": "python -u \"$file\"",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"},
"variants":
[
{
"name": "Syntax Check",
"shell_cmd": "python -m py_compile \"${file}\"",
}
]
}

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

Python3 in SublimeText3 configuration OSX

I have some programming experience in C++ but am trying to learn Python - I am struggling to get a "hello world" to display in Python3 via SublimeText 3 that I tried to configure today. Been reading through the many posts on this topic and have not yet solved my problem, appreciate any insight.
So far I have:
Installed Python3 and SublimeText3 today using .dmg utility
Confirmed Python3 is installed via terminal, and paths are "/usr/local/bin/python3" and "/Library/Frameworks/Python.framework/Versions/3.7/bin/python3"
Created new Python3.sublime-build file and saved to local "Users" directory with the following command:
{
"cmd": ["usr/local/bin/python3", "-u", "$file"],
}
I then changed the Sublime Text Build System to Python3 in the "Tools" menu.
Created and saved a new .py file. It built and ran successfully (Cmd + B) when prompted to print("Hello") but not when setting it to a variable
message = "Hello"
print(message)
It returns a syntax error:
File "/Users/username/python_files/hello.py", line 2
message = "Hello"
^
SyntaxError: invalid syntax
[Finished in 0.0s with exit code 1]
[cmd: ['/Library/Frameworks/Python.framework/Versions/3.7/bin/python3', '-u', '/Users/username/python_files/hello.py']]
[dir: /Users/username/python_work]
[path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
I saved the .py file before trying to build. I tried other variations for the sublime-build command based on user suggestions, but none have worked:
"cmd": ["/usr/local/bin/python3", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
Not really adept with Unix or OSX terminal so my own troubleshooting is a bit limited. Where should I be looking next to get this thing to work? Grateful for help, and eager to get started.
Did you try already to follow this instruction step-by-step? I just tried it and the instruction works.
From your code listing it seems, that you specify
{
"cmd": ["usr/local/bin/python3", "-u", "$file"],
}
while the Built-System Output says
[cmd: ['/Library/Frameworks/Python.framework/Versions/3.7/bin/python3', ...
There is a mix up of your python paths either on your system or in your listings. In the first case try to run python3 in your terminal and do
import sys
print(sys.executable)
This will give you your correct python path. Copy the path and paste it in the "cmd" statement of your .sublime-build file
"cmd": ["/path/to/your/python/python3", "-u", "$file"]
This should do it
Thanks guys for the helpful links - I sorted this out by realizing that my entire python3 code was contained within {} brackets - apparently this is incorrect. To my credit, this formatting still ran with just the basic print("Text") within the brackets. Wish me luck with my journey of discovery, sounds like I'll need it...

How to run a Python program in Sublime Text without using command line [duplicate]

I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ?
Tools -> Build System -> (choose) Python then:
To Run:
Tools -> Build
-or-
Ctrl + B
CMD + B (OSX)
This would start your file in the console which should be at the bottom of the editor.
To Stop:
Ctrl + Break or Tools -> Cancel Build
Fn + C (OSX)
You can find out where your Break key is here: http://en.wikipedia.org/wiki/Break_key.
Note: CTRL + C will NOT work.
What to do when Ctrl + Break does not work:
Go to:
Preferences -> Key Bindings - User
and paste the line below:
{"keys": ["ctrl+shift+c"], "command": "exec", "args": {"kill": true} }
Now, you can use ctrl+shift+c instead of CTRL+BREAK
Edit %APPDATA%\Sublime Text 2\Python\Python.sublime-build
Change content to:
{
"cmd": ["C:\\python27\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
change the "c:\python27" part to any version of python you have in your system.
On Mac OS X, save your file with a .py extension. Press ⌘ + B. It runs in a window below.
To RUN press CtrlB (answer by matiit)
But when CtrlB does not work, Sublime Text probably can't find the Python Interpreter. When trying to run your program, see the log and find the reference to Python in path.
[cmd: [u'python', u'-u', u'C:\\scripts\\test.py']]
[path: ...;C:\Python27 32bit;...]
The point is that it tries to run python via command line, the cmd looks like:
python -u C:\scripts\test.py
If you can't run python from cmd, Sublime Text can't too.
(Try it yourself in cmd, type python in it and run it, python commandline should appear)
SOLUTION
You can either change the Sublime Text build formula or the System %PATH%.
To set your %PATH%:
*You will need to restart your editor to load new %PATH%
Run Command Line* and enter this command: *needs to be run as administrator
SETX /M PATH "%PATH%;<python_folder>"
for example: SETX /M PATH "%PATH%;C:\Python27;C:\Python27\Scripts"
OR manually: (preferable)
Add ;C:\Python27;C:\Python27\Scripts at the end of the string.
To set the interpreter's path without messing with System %PATH% see this answer by ppy.
You can use SublimeREPL (you need to have Package Control installed first).
If using python 3.x you need to edit the Python3.sublime-build
(Preferences > Browse packages > Python 3)
to look like this:
{
"path": "/usr/local/bin",
"cmd": ["python3", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
[ This applies to ST3 (Win), not sure about ST2 ]
To have the output visible in Sublime as another file (+ one for errors), do this:
Create a new build system: Tools > Build Systems > New Build System...
Use the following configuration:
{
"cmd": ["python.exe", "$file", "1>", "$file_name.__STDOUT__.txt", "2>", "$file_name.__STDERR__.txt"],
"selector": "source.python",
"shell": true,
"working_dir": "$file_dir"
}
For your Python file select the above build system configuration file: Tools > Build Systems > {your_new_build_system_filename}
ctrl + b
Now, next to your file, e.g. "file.py" you'll have "file.__STDOUT__.py" and "file.__STDERR__.py" (for errors, if any)
If you split your window into 3 columns, or a grid, you'll see the result immediately, without a need to switch panels / windows
In python v3.x you should go to : Tools->Build System->New Build System.
Then, it pop up the untitled.sublime-build window in sublime text editor.Enter setting as:
{
"cmd": ["path_to_the_python.exe","-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
To see the path, Type following in terminal as:
python
>>> import sys
>>>print(sys.executable)
You can make more than one Build System but it should default save inside Packages of Sublime text with .sublime-build extension.
Then, select the new Build System and press cltr+b or other based on your os.
Cool U guys, I just found this:
http://ptomato.wordpress.com/2012/02/09/geek-tip-running-python-guis-in-sublime-text-2/
It explains (like one of the answers above) how to edit this exec.py in the default directory.
I had the problem that my PYTHON UI APPLICATION would not start. I commented out the last line from the following snipped:
# Hide the console window on Windows
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
#startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
and, taaadaaaa, I could start my app by pressing Ctrl+B. Funny line anyways, uh? And a big thank you to whoever wrote that article ;-)
I solved this problem :
> Preferences –> Browse Packages –> Default
Open the exec.py file, near line 41-42, the code should look like this :
for k, v in proc_env.iteritems():
proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
then delete it or edit it as :
try:
for k, v in proc_env.iteritems():
proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
except:
print 'foobar'
I ran into the same problem today. And here is how I managed to run python code in Sublime Text 3:
Press Ctrl + B (for Mac, ⌘ + B) to start build system. It should execute the file now.
Follow this answer to understand how to customise build system.
What you need to do next is replace the content in Python.sublime-build to
{
"cmd": ["/usr/local/bin/python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
}
You can of course further customise it to something that works for you.
seems the Ctrl+Break doesn't work on me, neither the Preference - User...
use keys, Alt → t → c
You can access the Python console via “View/Show console” or Ctrl+`.
I had the same problem. You probably haven't saved the file yet. Make sure to save your code with .py extension and it should work.
One thing to note about the aforementioned build system: you can write (and use) custom .sublime-build files or even per project build_systems clause (in your project settings). This allows you to do useful things like a fancy test runner with ANSI colors output.
For even more "full IDE" features, you can use the excellent SublimePythonIDE package:
code completion (intel)
jump to definition & object description
proper linting/pep8
supports different interpreters with virtualenv
Disclosure: I've contributed a PR to that package, and I use it all the time, but there are others.
Use a real python console alongside Sublime
Both Sublime's build system and SublimeREPL (the answers above) are limited in that you can't easily interact with the workspace variables after you run your file.
If you want to run a script, then work in a REPL-like fashion (like you would in an IDE), then I recommend having Sublime open alongside an IPython console. Using AutoHotKey (Windows) or AutoKey (Linux), you can set this up such that a single shortcut will copy the filename (or just the selected code) and then paste this in the console to run the file.
Detailed instructions for Linux or Windows

Set up Python 3 build system with Sublime Text 3

I want to configure Sublime Text 3 to build Python 3, but I don't seem to understand how the builds work. Many tutorials have told me to make a build file containing code such as:
{
'cmd': ['/usr/bin/python3', '-u', '$file'],
'file_regex': '^[ ]*File "(…*?)", line ([0-9]*)',
'selector': 'source.python'
}
and save it as a file called Python.sublime-build or python3.sublime-build (much of the information I found was conflicting). One tutorial suggested creating a new folder in the ST3 Packages folder called Python and add the build file in there, whilst other tutorials suggested leaving it in the folder called User.
One tutorial explained how I had to change the Environment Variable path on my operating system to get it to work. That didn't seem to help either.
I added a folder Python to Packages (since it wasn't there already) and added in a build file with the name Python.sublime_build which featured only the code I posted above in it. Now when I attempt to run Sublime Text it gives me this error:
Error trying to parse build system:
Expected value in Packages\Python\Python.sublime-build:2:5
The reason you're getting the error is that you have a Unix-style path to the python executable, when you're running Windows. Change /usr/bin/python3 to C:/Python32/python.exe (make sure you use the forward slashes / and not Windows-style back slashes \). Once you make this change, you should be all set.
Also, you need to change the single quotes ' to double quotes " like so:
{
"cmd": ["c:/Python32/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
The .sublime-build file needs to be valid JSON, which requires strings be wrapped in double quotes, not single.
Steps to Make Sublime Text a Python IDE (Windows)
Tested successfully on Sublime Text 3. Assuming Sublime Text and package control are already installed . . .
Install Python (python.org) and pay attention to where it is installed or choose a simple location like the C drive, agreeing to remove character limit at the end of the installation.
Install package SublimeREPL (Cntrl + Shift + P, Package Control - Install Package, SublimeREPL, Enter).
Go to Preferences, Package Settings, SublimeREPL, Settings - User.
Paste in the following, updating the file path to your python installation folder, as needed. You may customize these and choose whatever syntax you like (last line) but I prefer my output in plain text.
{
"default_extend_env": {"PATH":"C:\\Program Files\\Python36\\"},
"repl_view_settings": {
"translate_tabs_to_spaces": false,
"auto_indent": false,
"smart_indent": false,
"spell_check": false,
"indent_subsequent_lines": false,
"detect_indentation": false,
"auto_complete": true,
"line_numbers": false,
"gutter": false,
"syntax": "Packages/Text/Plain text.tmLanguage"
}
}
Save and close the file (SublimeREPL.sublime-settings).
Go to Tools, Build System, New Build System.
Replace all existing text with the following:
{
"target": "run_existing_window_command",
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
Cntrl + S or save as "C:\Users[username]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL-python.sublime-build" updating username or path as needed. This should be wherever your settings and builds are stored by Sublime Text.
Go to Tools, Build System, select SublimeREPL-python.
All done--now to test. Open or create a simple python file, having a *.py extension and save it wherever desired.
Make sure the file is open and selected in Sublime Text. Now, when you press Cntrl + B to build and run it, it will open another tab, titled "REPL [python]", executing and displaying the results of your python code.
If you would like to go a step further, I highly recommend making the follow changes, to allow Sublime to reload your executed python in the same window, when you press Cntrl+B (Build), instead of it opening a new tab each time:
Add the following line in the "repl_python_run" command in (Preferences, Browse Packages) SublimeREPL\config\Python\Main.sublime-menu, right before the "external_id": "python" argument:
"view_id": "*REPL* [python]",
and then to change the line:
if view.id() == view_id
into:
if view.name() == view_id
in SublimeREPL\sublimerepl.py.
If you are using PyQt, then for normal work, you should add "shell":"true" value, this looks like:
{
"cmd": ["c:/Python32/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"shell":"true"
}
Run Python Files in Sublime Text3
For Sublime Text 3,
First Install Package Control:
Press Ctrl + Shift + P, a search bar will open
Type Install package and then press enter
Click here to see Install Package Search Pic
After the package got installed. It may prompt to restart SublimeText
After completing the above step
Just again repeat the 1st and 2nd step, it will open the repositories this time
Search for Python 3 and Hit enter.
There you go.
Just press Ctrl + B in your python file and you'll get the output.
Click here to see Python 3 repo pic
It perfectly worked for me. Hopefully, it helped you too.
For any left requirements, visit https://packagecontrol.io/installation#st3 here.
Steps for configuring Sublime Text Editor3 for Python3 :-
Go to preferences in the toolbar.
Select Package Control.
A pop up will open.
Type/Select Package Control:Install Package.
Wait for a minute till repositories are loading.
Another Pop up will open.
Search for Python 3.
Now sublime text is set for Python3.
Now go to Tools-> Build System.
Select Python3.
Enjoy Coding.
Version for Linux. Create a file ~/.config/sublime-text-3/Packages/User/Python3.sublime-build with the following.
{
"cmd": ["/usr/bin/python3", "-u", "$file"],
"file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"
}
And to add on to the already solved problem, I had installed Portable Scientific Python on my flash drive E: which on another computer changed to D:, I would get the error "The system cannot find the file specified". So I used parent directory to define the path, like this:
From this:
{
"cmd": ["E:/WPy64-3720/python-3.7.2.amd64/python.exe", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
To this:
{
"cmd": ["../../../../WPy64-3720/python-3.7.2.amd64/python.exe","$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
You can modify depending on where your python is installed your python.
first you need to find your python.exe location, to find location run this python script:
import sys
print(sys.executable)
Then you can create your custom python build:
{
"cmd": ["C:\\Users\\Sashi\\AppData\\Local\\Programs\\Python\\Python39\\python.exe", "-u", "$file"],
"file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"}
You can change the location, In my case it is C:\Users\Sashi\AppData\Local\Programs\Python\Python39\python.exe
Then save your new build. Don't change the file extension while saving.
I'd like to add just one point to the accepted answer:
when you edit the cmd portion of the snippet below, make sure to add the file address (with forward slash) where python is kept on your computer.
{
"cmd": ["c:/Python32/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
How to know where python is installed on your system? Two ways for windows users:
Open Command prompt and do the following query: where python
If it shows the path to python.exe, copy and paste it with /. If it shows some error, then follow process below:
Go to start -> Search for python shortcut (not IDLE) -> Right Click -> More -> Open file location -> Right click the shortcut -> Properties -> Target -> Path is now visible -> Copy and paste it in the field above.
Here is a very simple Python Sublime Text build system that works when python scripts are invoked with py file_name.py.
Just create py.sublime-build by Tools > Build System > New Build System and add the contents below:
{
"cmd": ["python3", "$file"]
}
You can select it in Sublime Text editor by going to Tools > Build System > py and building with Ctrl + b.
Note: If your filesystem doesn't python3 than you need to provide path/to/python3 and it should work.

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