[ANN] isrealfile function

M

Manlio Perillo

Hi.
Maybe this function can be useful for someone:


import os

def isrealfile(file):
"""
Test if file is on the os filesystem
"""

if not hasattr(file, 'fileno'): return False

try: tmp = os.dup(file.fileno())
except: return False
else: os.close(tmp); return True


I have implemented this function for testing if a Python script is
being executed by Python.exe or Pythonw.exe. In the latter case, in
fact, Microsoft implementation of stdout/stderr is broken.


[sitecustumize.py]
import sys

if not isrealfile(sys.__stdout__): sys.stdout = NullStream()
if not isrealfile(sys.__stderr__): sys.stderr = NullStream()


Where NullStream is a file like class that writes nothing.



P.S.
I have only tested this function on Windows XP Pro.


Regards Manlio Perillo
 
P

Peter Hansen

Manlio said:
def isrealfile(file):
"""
Test if file is on the os filesystem
"""

if not hasattr(file, 'fileno'): return False

try: tmp = os.dup(file.fileno())
except: return False
else: os.close(tmp); return True

I have implemented this function for testing if a Python script is
being executed by Python.exe or Pythonw.exe. In the latter case, in
fact, Microsoft implementation of stdout/stderr is broken.

I haven't tested this idea, but wouldn't "os.isatty()" be
the right thing for this purpose, instead of the os.dup()
and os.close() stuff?

-Peter
 
M

Manlio Perillo

I haven't tested this idea, but wouldn't "os.isatty()" be
the right thing for this purpose, instead of the os.dup()
and os.close() stuff?

Yes, it works (but the documentation says that isatty is available
only on Unix!).

However there is a problem:

pythonw ascript.py > afile

In this case sys.stdout is not a tty but it is a real file (so I can
write on it).
isrealfile is only(?) useful for Microsoft Windows because 'pseudo'
stdout and stderr used by pythonw.exe are not real files and are
broken (if you write more than 4096 characters an exception is
raised!).

Probably a more logical solution is to simply close stdout and stderr.
However by connecting them to a NullStream is more useful (at least
for me).




Regards Manlio Perillo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,052
Members
47,656
Latest member
rickwatson

Latest Threads

Top