tags:

views:

931

answers:

4

When I execute "python" from the terminal with no arguments it brings up the Python interactive shell.

When I execute "cat | python" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe.

How would I do a similar detection in C or C++ or Qt?

+3  A: 

Call stat() or fstat() and see if S_IFIFO is set in st_mode.

sigjuice
+2  A: 

Probably they are checking the type of file that "stdin" is with fstat, something like this:

struct stat stats;
fstat(0, &stats);
if (S_ISCHR(stats.st_mode)) {
    // Looks like a tty, so we're in interactive mode.
} else if (S_ISFIFO(stats.st_mode)) {
    // Looks like a pipe, so we're in non-interactive mode.
}

But why ask us? Python is open source. You can just go look at what they do and know for sure:

http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tar.bz2

Hope that helps,

Eric Melski

Eric Melski
+1  A: 

You can call stat() and check for !S_ISREG( result.st.mode ). That's Posix, not C/C++, though.

+14  A: 

Use isatty:

#include <stdio.h>
#include <io.h>
...    
if (isatty(fileno(stdin)))
    printf( "stdin is a terminal\n" );
else
    printf( "stdin is a file or a pipe\n");

(On windows they're prefixed with underscores: _isatty, _fileno)

RichieHindle
+1: stdin can be a pipe or redirected from a file. Better to check if it *is* interactive than to check if it is *not*.
John Kugelman