Python Forum
Cannot print if 'sys.stdout' is in snipped
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot print if 'sys.stdout' is in snipped
#1
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.
Reply
#2
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
Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020