How do I run Python code from Sublime Text 2?
Asked Answered
S

15

317

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 ?

Stylus answered 18/12, 2011 at 12:36 Comment(0)
A
380

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

Asir answered 18/12, 2011 at 13:49 Comment(6)
sublime text can also "auto detect" the language. So it worked for me to just CTRL + BGoethe
Make sure python is in your PATH... the windows installer doesn't seem to do this automagicallyScyphate
My keyboard's break key looks like "Pause/Break", so to stop process I also added {"keys": ["pause"], "command": "exec", "args": {"kill": true} }Beers
Having the line {"keys": ["ctrl+shift+c"], "command": "exec", "args": {"kill": true} } in User key bindings and using ctrl+shift+c prints that the build is [Cancelled] while the program still being run.Paripinnate
In IDLE you can continue to use the shell your code runs in (to inspect objects, try more code, etc.). How do we do this in Sublime?Roe
@matiit, it's cool, but how can I process user's input? something like guessNumber = input if guessNumber > 10: do_something()? after I input number, and press enter, sublime console start new line instead of processing `if statement.Chinoiserie
J
56

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.

Joshuajoshuah answered 7/3, 2012 at 19:19 Comment(4)
Pay attention to the double slash in the path, Sublime won't recognize it otherwise!Michellemichels
Single forward slash also works in place of double backslash on Windows: "C:/Python27/python.exe" (à la Linux and OSX)Importunity
For me the path was %APPDATA%\Sublime Text 2\Packages\Python\Python.sublime-buildPovertystricken
I don't seem to see the Python folder in Sublime Text 3Nous
F
56

On Mac OS X, save your file with a .py extension. Press + B. It runs in a window below.

enter image description here

Fincher answered 14/6, 2013 at 15:26 Comment(0)
G
44

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. Setting Path in Win7

  • To set the interpreter's path without messing with System %PATH% see this answer by ppy.

Gangland answered 12/2, 2013 at 13:35 Comment(2)
Sorry but can you explain what is the meaning of option "-u"? I cannot find the list option of command line params to pass together with python.exe.Nolpros
@JimRaynor it's unbuffered streams https://mcmap.net/q/25571/-python-significance-of-u-optionGangland
S
6

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"
}
Simulation answered 28/4, 2014 at 17:13 Comment(0)
C
5

[ This applies to ST3 (Win), not sure about ST2 ]

To have the output visible in Sublime as another file (+ one for errors), do this:

  1. Create a new build system: Tools > Build Systems > New Build System...
  2. 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"
    }
  1. For your Python file select the above build system configuration file: Tools > Build Systems > {your_new_build_system_filename}
  2. ctrl + b
  3. Now, next to your file, e.g. "file.py" you'll have "file.__STDOUT__.py" and "file.__STDERR__.py" (for errors, if any)
  4. If you split your window into 3 columns, or a grid, you'll see the result immediately, without a need to switch panels / windows
Capriole answered 19/11, 2016 at 6:7 Comment(0)
S
3

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.

Sharitasharity answered 6/12, 2017 at 8:8 Comment(0)
L
2

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 ;-)

Looker answered 14/6, 2013 at 20:12 Comment(0)
C
1

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'
Coreen answered 8/1, 2013 at 8:35 Comment(3)
what does it do actually? How does it help?Gangland
@Gangland He thought the program should handle exceptions so he put the code in a try block.Anderegg
I tried this. It didn't fix the problem, and it broke the existing behavior.Casanova
C
1

I ran into the same problem today. And here is how I managed to run python code in Sublime Text 3:

  1. Press Ctrl + B (for Mac, + B) to start build system. It should execute the file now.
  2. 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.

Causation answered 30/1, 2017 at 6:58 Comment(0)
E
1

seems the Ctrl+Break doesn't work on me, neither the Preference - User...

use keys, Alt → t → c

Event answered 15/7, 2020 at 3:0 Comment(0)
S
0

You can access the Python console via “View/Show console” or Ctrl+`.

Sharlenesharline answered 18/12, 2011 at 13:24 Comment(4)
but it shows the following error : File ".\exec.py", line 109, in run File ".\ntpath.py", line 205, in dirname File ".\ntpath.py", line 170, in split File ".\ntpath.py", line 125, in splitdrive TypeError: 'NoneType' object is unsubscriptableStylus
Please give more details (by expanding the question) on what you are doing.Sharlenesharline
i just type in python code like print 'hello' and then build it and open the console to see this error.Stylus
Using the Python console does not answer the question. The embedded interpreter is intended only to interact with the plugin API, not for general development.Trass
S
0

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.

Softshoe answered 28/4, 2012 at 11:45 Comment(0)
J
0

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.

Jessjessa answered 4/5, 2015 at 12:38 Comment(0)
B
0

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

Belden answered 28/12, 2017 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.