Python Forum

Full Version: Cannot print if 'sys.stdout' is in snipped
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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! Wink
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_stdout
It would be even better to use a context to ensure that sys.stdout is restored in the end.