python:找出是否在shell中运行(例如sun grid engine queue)

7 python shell terminal stdout

有没有办法从python程序中找出它是在终端中启动还是在像太阳网格引擎这样的批处理引擎中启动?

我的想法是决定是否打印一些进度条和其他ascii-interactive的东西.

谢谢!

页.

Die*_*Epp 13

标准的方法是isatty().

import sys
if sys.stdout.isatty():
    print("Interactive")
else:
    print("Non-interactive")
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 6

您可以使用它os.getppid()来查找此父进程的进程ID,然后使用该进程ID来确定该进程正在运行的程序.更有用的是,您可以使用sys.stdout.isatty()- 这不会回答您的标题问题,但似乎更好地解决您解释的实际问题(如果您在shell下运行但输出通过管道传输到其他进程或重定向到文件您也许不想在它上面发出"互动的东西").