chasmani
chasmani

Reputation: 2510

Sublime Text 3 Python 3 print while running

I can't get Python 3 to print out anything while running a script in Sublime Text. I can get it to print out after the script has finished, but I need it to print as it goes.

Here's some example code

import time

    for x in range(10):
        print("Test")
        time.sleep(1)

Using Python 3 as the build system, I get nothing for 10 seconds, and then 10 "Tests" printed all at once.

If I run the same script using the Python 2 build system, I get 1 "Test" printed out each second, which is what I want.

Similarly if I run the script using "python3 script.py" in the terminal I get 1 "Test" printed out each second.

Can anyone tell me how to make the build system in Sublime Text 3 print out Python 3 while it runs?

Upvotes: 3

Views: 537

Answers (1)

Delgan
Delgan

Reputation: 19677

You have to open your Python 3 build system configuration file, and ensure that the -u option is supplied to the command line to be executed.

For example:

# ~/.config/sublime-text-3/Packages/User/Python3.sublime-build
{
    "cmd": ["/usr/bin/python3.5", "-u", "$file"],
    "selector": "source.python",
    "file_regex": "file \"(...*?)\", line ([0-9]+)"
}

Quoting the documentation:

-u

Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. The text I/O layer will still be line-buffered if writing to the console, or block-buffered if redirected to a non-interactive file.

With this option, the ouptut of your Python script will be correctly displayed into Sublime Text while running.

Upvotes: 2

Related Questions