Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I revert sys.stdout.close()?

Tags:

python

In the interactive console:

>>> import sys
>>> sys.stdout
<open file '<stdout>', mode 'w' at 0xb7810078>
>>> sys.stdout.close()
>>> sys.stdout # confirming that it's closed
(...) ValueError: I/O operation on closed file

Attempting to revert:

>>> sys.stdout.open()
(...) AttributeError: 'file' object has no attribute 'open'
>>> sys.stdout.write('foo')
(...) ValueError: I/O operation on closed file

I agree that it's a frivolous question, but I'm curious how sys.stdout.close() can be reverted in Python (without restarting the interactive console, of course) and why sys.stdout.open() does not make sense.

like image 789
ammt Avatar asked Dec 02 '22 18:12

ammt


1 Answers

Okay, so I hope you are on a unix system...

Basically sys.stdout is just a variable containing any writable object.

So we can do magic like

sys.stdout = open("file", "w")

and now we can write to that file as if it was stdout.

Knowing unix is just one big box of files. Unix is kind enough to give us /dev/stdout

So to re-open stdout its simple

sys.stdout = open("/dev/stdout", "w")

Job done, you now have a new stdout opened up.

Edit

>>> os.fstat(1)
posix.stat_result(st_mode=8592, st_ino=7, st_dev=11L, st_nlink=1, st_uid=1000, st_gid=5, st_size=0, st_atime=1374230552, st_mtime=1374230552, st_ctime=1374230434)
>>> sys.stdout.close()
>>> sys.stdout = open("/dev/stdout", "w")
>>> sys.stdout.fileno()
3
>>> os.fstat(3)
posix.stat_result(st_mode=8592, st_ino=7, st_dev=11L, st_nlink=1, st_uid=1000, st_gid=5, st_size=0, st_atime=1374230576, st_mtime=1374230576, st_ctime=1374230434)
>>> os.fstat(1)
posix.stat_result(st_mode=8592, st_ino=7, st_dev=11L, st_nlink=1, st_uid=1000, st_gid=5, st_size=0, st_atime=1374230576, st_mtime=1374230576, st_ctime=1374230434)
>>> 
like image 128
Jakob Bowyer Avatar answered Dec 12 '22 03:12

Jakob Bowyer