检查进程是否作为管道运行

jac*_*hab 10 python pipe process stdio

我有一个小的Python实用程序,它应该只作为管道运行.我希望它在单独运行时打印出帮助消息.一个过程如何知道它是否被用作管道.比较sys.stdinsys.__stdin__不起作用.

Mat*_*hen 13

你可以使用isatty:

if sys.stdin.isatty():
Run Code Online (Sandbox Code Playgroud)

这将是True如果标准输入是一个tty,大致意味着它是被直接使用,一个管的外侧.

  • 另外`如果sys.stdout.isatty()`相反. (2认同)