Cannot print if 'sys.stdout' is in snipped - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Networking (https://python-forum.io/forum-12.html) +--- Thread: Cannot print if 'sys.stdout' is in snipped (/thread-34090.html) |
Cannot print if 'sys.stdout' is in snipped - tester_V - Jun-25-2021 Greetings! Sorry if this is the wrong place for the post! I'm converting IPs to Hosts, and it works fine but I cannot print anything in the script because of 'sys.stdout' import socket import sys pfile = open("C:/01/IP_Active1.txt") h_active = open("C:/01/IP_Host_Active.txt","w") sys.stdout = h_active while True: IP = pfile.readline() print ("THIS IS the LIST",IP) if (""==IP) : print ("EOF") break else : try: host = socket.gethostbyaddr(IP.rstrip()) print(IP,host) h_active.write("IP,host") except Exception as e: print(IP,e) pfile.close() h_active.close() print(f" ------------------ TESTING ---------------------") ValueError: I/O operation on closed file.I have to tell you I do not completely understand how the snippet works, I got it from some website some time ago. Thank you. RE: Cannot print if 'sys.stdout' is in snipped - tester_V - Jun-25-2021 Well, found how to fixed it. Googled it for a couple of hours... sys.stdout = sys.__stdout__I do not know what it does but it fixed printing errors... Cheers! RE: Cannot print if 'sys.stdout' is in snipped - Gribouillis - Jun-25-2021 According to the documentation, a better way to do this is sys.stdout, old_stdout = h_active, sys.stdout ... h_active.close() sys.stdout = old_stdoutIt would be even better to use a context to ensure that sys.stdout is restored in the end. |