nar*_*nie 10 python testing shell user-interface
我在Linux的工作,我想知道如何让蟒蛇告诉它是否是直接从终端或通过GUI运行(如ALT-F2),其中输出需要被发送到一个窗口,而不是标准输出将出现在一个终端.
在bash中,这完成了:
if [ -t 0 ] ; then
echo "I'm in a terminal"
else
zenity --info --title "Hello" --text "I'm being run without a terminal"
fi
Run Code Online (Sandbox Code Playgroud)
如何在python中完成?换句话说,相当于[-t 0])?
$ echo ciao | python -c 'import sys; print sys.stdin.isatty()'
False
Run Code Online (Sandbox Code Playgroud)
Of course, your GUI-based IDE might choose to "fool" you by opening a pseudo-terminal instead (you can do it yourself to other programs with pexpect, and, what's sauce for the goose...!-), in which case isatty or any other within-Python approach cannot tell the difference. But the same trick would also "fool" your example bash program (in exactly the same way) so I guess you're aware of that. OTOH, this will make it impossible for the program to accept input via a normal Unix "pipe"!
A more reliable approach might therefore be to explicitly tell the program whether it must output to stdout or where else, e.g. with a command-line flag.