3

I would like to learn the difference between sys.stdout.write and print methods(or functions? Should I call them function or method?)

For example, the code below will print 11

a = str(1)
sys.stdout.write (a)

But this will print 1

a = str(1)
print (a)

Why is there such difference? Is there any way to make sys.stdout.write() print 1, not 11?

Thanks!

cs95
  • 379,657
  • 97
  • 704
  • 746
Rakanoth
  • 375
  • 1
  • 5
  • 14

4 Answers4

8

The return value for sys.stdout.write() returns the no. of bytes written. In this case 1 which also gets printed on the interactive interpret prompt for any expressions entered.

Example:

>>> import sys
>>> sys.stdout.write("foo")
foo3

If you wanted to hide this you could do this:

>>> nbytes = sys.stdout.write("foo\n")
foo
James Mills
  • 18,669
  • 3
  • 49
  • 62
4

It looks like sys.stdout.write returns the value it writes. So it doesn't print 11, it prints 1 and returns 1. However, if you do this in the interactive interpreter, the interpreter prints the return value of the expression, which is again 1.

If you don't do it in the interactive interpreter (i.e. you put your code in a file and run it), it won't print the second 1. In the interactive interpreter, you can suppress it by assigning the result:

x = sys.stdout.write(a)
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

I guess your next execution should throw the same result for both write and print .

As it was not printed in the first time and sits in stdout, it prints all the stdout at the same time i.e. 1 form previous execution and 1 from current execution.

Just try out and let me know :)

Sravan K Ghantasala
  • 1,058
  • 8
  • 14
2

To explain you the difference you have to understand print function -

print(*objects, sep=' ', end='\n', file=sys.stdout)

Print takes inputs objects and writes it to file arguement which by default is sys.stdout and returns Nothing. It uses write function of file arguement object and prints end arguement as last character That means it uses sys.stdout.write by default to print statement to the screen . Sys.stdout.write returns number of bytes as return value. Print is some wrapper on top of sys.stdout.write.

Arovit
  • 3,579
  • 5
  • 20
  • 24