So I've been trying to find an answer for this, including searching StackOverflow, and all the solutions I've found so far haven't worked.
Some background: My code reads in a file and does some things to each word. The code itself works, I'm just trying to get the output formatted. Specifically, my intent is that when I run the script, it should print a single line "Current word: [x]" where [x] is the word being processed at the time. It should overwrite itself over and over to display each word on the same line, as opposed to printing each line separately. Basically, it should be a textual progress bar.
I'm aware of \r, the carriage return, and that it should send the cursor back to the beginning of the line. At the moment, I can't use any combination of print() or sys.stdout.write() calls to avoid the newline, no matter what I try:
1, as per https://stackoverflow.com/a/20980840/6767203:
print("\rCurrent Word: " + currentWord, end="")
2:
print("Current Word: " + currentWord, end="\r")
3, because I thought maybe having everything contained in a single string might help (and it was the format of this answer):
print("\rCurrent Word: {0}".format(currentWord), end="")
4, as per https://stackoverflow.com/a/11018255/6767203:
import sys
[...]
sys.stdout.write("\rCurrent Word: {0}".format(currentWord))
sys.stdout.flush() #tried with and without this
5, as per https://stackoverflow.com/a/11076668/6767203:
import sys, os
[...]
sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)
[...]
print("\rCurrent Word: {0}".format(currentWord))
# tried all the previous print()s and sys.stdout.write()s, too
None of these produce errors, but all of them fail to remove the newline, resulting in a big stack of lines being printed to the screen. (I think some of these may result in two lines; I tried a lot of things, and I forget the exact outputs of each variant.)
I did some playing around, and
sys.stdout.write("Current \rWord: {0}".format(currentWord))
does shift the cursor to the left like expected, resulting in "Word: [x]" (and some cruft every so often) -- it just also prints a newline.
I'm writing the script to 'script.py', and then in a terminal window,
chmod 777 script.py
./script.py
with
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
at the top. I'm also running Mac OS X 10.9.5, if that makes a difference.