source

sys.stdout이 터미널에 연결되어 있는지 여부를 탐지하려면 어떻게 해야 합니까?

itover 2023. 6. 6. 10:42
반응형

sys.stdout이 터미널에 연결되어 있는지 여부를 탐지하려면 어떻게 해야 합니까?

그들이 그들을sys.stdout콘솔 터미널에 연결되어 있습니까?예를 들어, foo.py 이 다음을 통해 실행되는지 여부를 검색할 수 있습니다.

$ python foo.py  # user types this on console

OR

$ python foo.py > output.txt # redirection
$ python foo.py | grep ....  # pipe

이 질문을 하는 이유는 진행률 표시줄 표시가 전자의 경우(실제 콘솔)에서만 발생하는지 확인하기 위해서입니다.

이 문제는 다음을 사용하여 감지할 수 있습니다.

if sys.stdout.isatty():
    # You're running in a real terminal
else:
    # You're being piped or redirected

셸에서 이를 시연하는 방법:

  • python -c "import sys; print(sys.stdout.isatty())"True라고 적어야 합니다.
  • python -c "import sys; print(sys.stdout.isatty())" | catFalse라고 적어야 합니다.

언급URL : https://stackoverflow.com/questions/1077113/how-do-i-detect-whether-sys-stdout-is-attached-to-terminal-or-not

반응형