python:找出是否在shell中运行(例如sun grid engine队列)
有没有办法从 python 程序中找出它是否是在终端中启动的,或者是在像 Sun Grid Engine 这样的批处理引擎中启动的?
这个想法是决定是否打印一些进度条和其他 ASCII 交互式内容。
谢谢!
p。
is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?
the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.
thanks!
p.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我发现以下内容在 Linux 和 Windows 上,在普通的 Python 解释器和 IPython 中都可以工作(尽管我不能说 IronPython):
但是,请注意,在使用 ipython 时,如果文件被指定为命令行参数,它将在解释器变为交互式之前运行。 看看我的意思如下:
HTH
I have found the following to work on both Linux and Windows, in both the normal Python interpreter and IPython (though I can't say about IronPython):
However, note that when using ipython, if the file is specified as a command-line argument it will run before the interpreter becomes interactive. See what I mean below:
HTH
稍微短一点:
Slightly shorter:
您可以使用 os.getppid() 找出该进程的父进程的进程 ID,然后使用该进程 ID 来确定该进程正在运行哪个程序。 更有用的是,您可以使用 sys.stdout.isatty() - 这不会回答您的标题问题,但似乎可以更好地解决您解释的实际问题(如果您在 shell 下运行但您的输出通过管道传输到其他进程或重定向到您可能不想在其上发出“交互式内容”的文件)。
You can use
os.getppid()
to find out the process id for the parent-process of this one, and then use that process id to determine which program that process is running. More usefully, you could usesys.stdout.isatty()
-- that doesn't answer your title question but appears to better solve the actual problem you explain (if you're running under a shell but your output is piped to some other process or redirected to a file you probably don't want to emit "interactive stuff" on it either).标准方法是 istty()。
The standard way is
isatty()
.