Python trailing comma after print executes next instruction - python

If a trailing comma is added to the end of a print statement, the next statement is executed first. Why is this? For example, this executes 10000 ** 10000 before it prints "Hi ":
print "Hi",
print 10000 ** 10000
And this takes a while before printing "Hi Hello":
def sayHello():
for i in [0] * 100000000: pass
print "Hello"
print "Hi",
sayHello()

In Python 2.x, a trailing , in a print statement prevents a new line to be emitted.
In Python 3.x, use print("Hi", end="") to achieve the same effect.
The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.

You're seeing the effects of stdout buffering: Disable output buffering

As others mention, standard out is buffered. You can try using this at points that you need the output to appear:
sys.stdout.flush()

print automatically puts a newline at the end of a string. This isn’t necessarily what we want; for example, we might want to print several pieces of data separately and have them all appear on one line. To prevent the newline from being added, put a comma at the end of the print statement:
d=6
print d,
print d
Output:
6 6

Related

Why `print '1\x08'` results 1 meanwhile `print '1\x082'` results 2?

Today, I'm learning the built-in function chr. And through ascii-table search, I found \x08 means backspace. So I played a bit with it. But the result confused me:
In [52]: print '1\x08'
1
In [53]: print '1\x082'
2
It seems that only follow by another character, \x08 will behave like a backspace, why does this happened? How \x08 behaves in a string?
It's behaving like a backspace in both cases, which is to say it moves your cursor back one space. It does not, however, delete what's there unless you write something else. So in the first case, the 1 remains, but in the second it is overwritten with a 2.
Backspace only moves the cursor by one character, it does not actually delete it. This for example results in 193:
print('123\x08\x089')
You can use space to actually "delete" the character...
1---- backspace simply move the cursor to the left one space, and
if you use the work or other editor it will also delete the left one character.
and what you must know is that backspace is also a character the same as 1 or a.
2---- the terminal as our default output device, you can also put him as a file.
So if you use
print '1\x08'
it means that you write a 1 and a backspace in the file stdout.
if you read the file, the system reads 1 + breakspace, you will get an 1.
and if you use
print '1\x082'
it means that you write a 1, a backspace and a 2 in the file stdout.
if you read the file, the system get 1 + breakspace + 2, when you print them, you will only get an 2, because it covers the first 1 when you use backspace.
for detail you can see the next test code
if __name__ == "__main__":
print "1\x08"
print "1\x082"
f = open("1.txt", "w")
f.write("1\x08\x082")
f.close();
f = open("1.txt", "r")
str = f.readlines( )
print len(str), str
for s in str:
print "s=|" + s + "|"
you can see the string s=|1\x08\x082| display s=2|. becasue the |1 not display when backspace two times.

python: print using carriage return and comma not working

I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:
print('{0} imported\r'.format(tot),)
However, it still prints multiple lines when looped through. I have also tried
sys.stdout.write('{0} imported\r'.format(tot))
but this doesn't print anything to the console...
Anyone know what's going on with this?
If you want to overwrite your last line you need to add \r (character return) and end="" so that you do not go to the next line.
values = range(0, 100)
for i in values:
print ("\rComplete: ", i, "%", end="")
print ("\rComplete: 100%")
In the first case, some systems will treat \r as a newline. In the second case, you didn't flush the line. Try this:
sys.stdout.write('{0} imported\r'.format(tot))
sys.stdout.flush()
Flushing the line isn't necessary on all systems either, as Levon reminds me -- but it's generally a good idea when using \r this way.
I prefer to use the solution of Jan but in this way:
values = range(0, 101)
for i in values:
print ("Complete: ", i, "%", end="\r")
print ()

In python how can i print only the first line of stdout which results from a shell command

in the following for loop, i print the version number of program installed
for program in sub3_required_programs:
try:
version = subprocess.call([program, '-i'])
print version + '\n'
except:
exit
But i actually want only the first line which has the version number. How can i restrict the print to only the first line
You can do:
print version.split("\n")[0]
which gets first line (splitting on newline character) from the output.
The problem with the str.split('\n') approach is that the newline character can differ across platforms. You might have better luck doing:
print version.splitlines()[0]
What's the current print output? Unless you're running a version of Python that behaves differently, it looks like the return status of the call is the only thing being assigned to version.
Run command with arguments. Wait for command to complete, then return
the returncode attribute.
- docstring for subprocess.call
I bet the subprocess.call is the culprit, printing it's output to STDOUT. Even if you didn't have that print statement, you would still see all the output of the subprocess call due to the way the method works.
To grab the actual output, you might want to do something more like
lines = subprocess.Popen([program, '-i'], stdout=subprocess.PIPE).communicate()[0]
print lines.splitlines()[0] + '\n'
The communicate call returns the tuple (stdoutdata, stderrdata). You can read more about it in the docs. Everything else should be self-explanatory.
Split the string at the newline character, and use only the first element of the resulting list:
print version.split('\n')[0]

Print without newline under function doesn't work as it should [duplicate]

This question already has an answer here:
Why doesn't print output show up immediately in the terminal when there is no newline at the end?
(1 answer)
Closed last month.
I'm trying to create a progress bar in the terminal, by repeatedly printing # symbols on the same line.
When i tell Python to not add newlines - using print('#', end='') in Python 3 or print '#', in Python 2 - it prints as desired, but not until the whole function is finished. For example:
import time
i = 0
def status():
print('#', end='')
while i < 60:
status()
time.sleep(1)
i += 1
This should print '#' every second but it doesn't. It prints them all after 60 seconds. Using just print('#') prints it out every second as expected. How can I fix this?
You probably need to flush the output buffer after each print invocation. See How to flush output of Python print?
Python is buffering the output until a newline (or until a certain size), meaning it won't print anything until the buffer gets a newline character \n. This is because printing is really costly in terms of performance, so it's better to fill a small buffer and only print once in a while instead.
If you want it to print immediately, you need to flush it manually. This can be done by setting the flush keyword argument to True.
import time
word = "One letter at a time"
for letter in word:
print(letter, end='', flush=True)
time.sleep(0.25)
You can always use the strip() function.

Where does the newline come from in Python?

In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
print adds a newline by default. To avoid this, use a trailing ,:
print "Line 1 is",
print "big"
The , will still yield a space. To avoid the space as well, either concatenate your strings and use a single print statement, or use sys.stdout.write() instead.
From the documentation:
A '\n' character is written at the
end, unless the print statement ends
with a comma. This is the only action
if the statement contains just the
keyword print.
If you need full control of the bytes written to the output, you might want to use sys.stdout
import sys
sys.stdout.write("Line 1 is ")
sys.stdout.write("big!\n")
When not outputing a newline (\n) you will need to explicitly call flush, for your data to not be buffered, like so:
sys.stdout.flush()
this is standard functionality, use print "foo",

Categories

Resources