views:

362

answers:

3

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.

+4  A: 

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 use sys.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).

Alex Martelli
thank you for your explanation, Alex! that helps me a lot!p.
@pavel, thanks for letting me know, feedback always helps!
Alex Martelli
+6  A: 

The standard way is isatty().

import os
import sys
os.isatty(sys.stdout.fileno())
Dietrich Epp
thank you very much, works just as intended! exactly what i looked for.p.
A: 

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):

isInteractive = hasattr(sys, 'ps1') or hasattr(sys, 'ipcompleter')

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:

C:\>cat C:\demo.py
import sys, os

# ps1=python shell; ipcompleter=ipython shell
isInteractive = hasattr(sys, 'ps1') or hasattr(sys, 'ipcompleter')
print isInteractive and "This is interactive" or "Automated"

C:\>python c:\demo.py
Automated

C:\>python
>>> execfile('C:/demo.py')
This is interactive

C:\>ipython C:\demo.py
Automated       # NOTE! Then ipython continues to start up...

IPython 0.9.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [2]: run C:/demo.py
This is interactive    # NOTE!

HTH

Roark Fan