11
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\n")
cdll.msvcrt.printf(b"Printf function 2\n")
cdll.msvcrt.printf(b"Printf function 3\n")
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\n")
cdll.msvcrt.printf(b"Printf function 2\n")
cdll.msvcrt.printf(b"Printf function 3\n")
#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:
python
windows
ctypes