I'm following the docs/tutorial here: https://docs.python.org/3/library/ctypes.htmlpython3.8
In section "Calling Functions Continued" it has a snippet for running printf. I played around with it a bit, and I can't understand why the first statement below prints only 5 and not Hello? Why is the newline needed? (update: also why are the orders sometimes different i.e. "5 Hello" vs "Hello 6")
>>> libc = cdll.LoadLibrary("libc.so.6")
>>> libc.printf
<_FuncPtr object at 0x7f68e4d61880>
>>> printf = libc.printf
>>> printf(b"Hello")
5
Hello>>> printf(b"Hello","")
5
Hello>>> printf(b"Hello %S\n","World!")
Hello World!
13
>>> printf(b"Hello\n","")
Hello
6
I suppose it might have something to do with this statement made on the same page:
Note that printf prints to the real standard output channel, not to sys.stdout, so these examples will only work at the console prompt, not from within IDLE or PythonWin:
But I can't really understand this statement, I always thought sys.stdout was the real system output channel. (perhaps these applications set it to something different)?
setup: python 3.8 running inside a linux docker container on a Mac
CodePudding user response:
The reason it's not printing a newline is because it's Python's native print
function that normally adds a newline. The libc
printf
implementation (what you would call if you were writing in C) does not print a newline at the end. You must explicitly add it.
As for the sys.stdout
vs "real standard out", "real standard out" writes to file descriptor 1. sys.stdout
ultimately does as well, but it goes through some code that the IDLE/PythonWin likely capture and process. So using printf
would circumvent those things, and therefore wouldn't show up. Not sure how it's implemented so that it doesn't, but that's the difference between them.