I'm trying to redirect the output of printf functions to a file on Windows. I'm using ctypes with python3 to invoke the functions. My code is:
import os, sys
from ctypes import *
if __name__ == '__main__':
print("begin")
saved_stdout=os.dup(1)
test_file=open("TEST.TXT", "w")
os.dup2(test_file.fileno(), 1)
test_file.close()
print("python print")
cdll.msvcrt.printf(b"Printf function 1
")
cdll.msvcrt.printf(b"Printf function 2
")
cdll.msvcrt.printf(b"Printf function 3
")
os.dup2(saved_stdout, 1)
print("end")
But when I run the code from Eclipse I get the following on the screen:
begin
end
Printf function 1
Printf function 2
Printf function 3
...and the following in the TEST.txt
python print
When I run this from cmd, this is what is on the screen:
begin
end
..and this is in the TEST.txt:
python print
When I comment out the second dup2()
statement e.g.
import os, sys
from ctypes import *
if __name__ == '__main__':
print("begin")
saved_stdout=os.dup(1)
test_file=open("TEST.TXT", "w")
os.dup2(test_file.fileno(), 1)
test_file.close()
print("python print")
cdll.msvcrt.printf(b"Printf function 1
")
cdll.msvcrt.printf(b"Printf function 2
")
cdll.msvcrt.printf(b"Printf function 3
")
#os.dup2(saved_stdout, 1)
print("end")
From Eclipse, on the screen:
begin
...and in the TEST.txt file:
python print
end
Printf function 1
Printf function 2
Printf function 3
From cmd, on the screen:
begin
...and in the TEST.txt file:
python print
end
I'm totally confused now. I read all the redirection threads here on StackOverflow and I can't understand what's going on.
Anyway, what I've gathered is that C functions access the stdout that is bind directly to the file descriptor, while python uses a special object for that - stdout File Object. So the elementary sys.stdout=*something*
doesn't work with ctypes.
I've even tried os.fdopen(1)
on the dup2-ed output and then calling flush()
after every printf
statement but this isn't working again.
I'm totally out of ideas now and would appreciate if someone have a solution for this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…