Skip to content

Instantly share code, notes, and snippets.

@yunruse
Created February 5, 2022 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yunruse/4251d37befa4468ff19c46d7b71b3b05 to your computer and use it in GitHub Desktop.
Save yunruse/4251d37befa4468ff19c46d7b71b3b05 to your computer and use it in GitHub Desktop.
Output to stdout only if currently being redirected with > or >>
from os import fstat
from stat import S_ISREG
def is_redirected() -> bool:
'''Detect if program is being redirected (i.e. using the > or >> operator).'''
return S_ISREG(fstat(1).st_mode)
if __name__ == '__main__':
if is_redirected():
print('Hi file!')
$ python redirect.py
$ python redirect.py | cat
$ python redirect.py > e.txt && cat e.txt
Hi file!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment