当前位置: 动力学知识库 > 问答 > 编程问答 >

pipe - Is there a way for a python script to "know" if it is being piped to?

问题描述:

myscript.py

import sys

if something_to_read_from_stdin_aka_piped_to:

cmd = sys.stdin.read()

print(cmd)

else:

print("standard behavior")

Bash example:

echo "test" | python myscript.py

If it is not being piped to, it would hang.

What is the way to know if the script should or should not read from stdin; I'm hoping there's something obvious other than a command line argument for the script.

网友答案:

Yes it is very much possible, I have modified your example to achieve this.

import sys
import os
if not os.isatty(0):
    cmd = sys.stdin.read()
    print(cmd)
else:
    print("standard behavior")

As we know 0 is file descriptor for input to program. isatty is test to check file descriptor refer to terminal or not. As pointed out by other user above approach will tell whether program is reading from terminal or not. However above programming solves the purpose of question but still there is room to improve. We can have another solution which will just detect if program is reading from pipe or not.

import sys
import os
from stat import S_ISFIFO

if S_ISFIFO(os.fstat(0).st_mode):
    print("Reading from pipe")
    cmd = sys.stdin.read()
    print(cmd)
else:
    print("not reading from pipe")
分享给朋友:
您可能感兴趣的文章:
随机阅读: