I am using the powerful Sublime Text 3 editor on MacOSX to run python codes. I want to display a progress bar of a for loop, and the following command:
sys.stdout.write('\rProgress : %03.2f %%' % (100*float(i)/(N)))
sys.flush()
does not clear the previously printed line in the output window as expected (\r
) but produces N
lines:
Progress : 0.25 %
Progress : 0.50 %
Progress : 0.75 %
Progress : 1.00 %
Progress : 1.25 %
Progress : 1.50 %
Progress : 1.75 %
Progress : 2.00 %
Progress : 2.25 %
Progress : 2.50 %
...
Which is not really nice to read – I conclude that the output window might be read-only.
Does anyone have suggestions to improve the use of progress bars in Sublime Text?
Unfortunately, this is not possible in Sublime's output panel. The panel is not a true console or terminal, and among other differences does not interpret escape sequences such as \r
and \b
(\n
is interpreted correctly, however). If you want to see how exactly it works, install PackageResourceViewer
, then open Packages/Default/exec.py
.
In order to get this to work, you'll need to create a new build system to run it in Terminal. Due to the vagaries of OS X, you'll need to create two files. The first is a shell script:
#!/bin/sh
osascript -e '
on run parameters
tell application "Terminal"
activate
do script with command "/path/to/python " & parameters
end tell
end run
' $@
Change /path/to
with your actual path to python
(or python3
). Save it wherever you want as PythonTerminal.sh
. Next, select Tools -> Build System -> New Build System
and paste in the following:
{
"cmd": ["/bin/sh /path/to/Python3Terminal.sh \"$file\""],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"shell": true
}
Again, change /path/to
to the actual path to PythonTerminal.sh
. Save the file as Packages/User/PythonTerminal.sublime-build
(it should automatically open the correct directory when saving).
Finally, select Tools -> Build System -> PythonTerminal
, switch to your Python file, and build with ⌘B. A new Terminal window will open and your progress bar should run.