Redirecting sys.stdout: Assigning print output to a file

Redirecting sys.stdout: Assigning print output to a file

Want stdout from your Python program to go elsewhere? Assign sys.stdout to a writeable file. (Don’t forget to keep the original around!)

old_stdout = sys.stdout
sys.stdout = open('/tmp/output.txt', 'w')
print('hello???')   # goes to /tmp/output.txt

Better: print’s file kwarg.