Created
February 5, 2022 16:07
-
-
Save yunruse/4251d37befa4468ff19c46d7b71b3b05 to your computer and use it in GitHub Desktop.
Output to stdout only if currently being redirected with > or >>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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