Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if stdout for a Python process is redirected

Tags:

python

I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).

Is there a reasonable way to do this in a Python script? So:

$ python my_script.py
Not redirected

$ python my_script.py > output.txt
Redirected!

like image 548
Jeffrey Harris Avatar asked Oct 03 '09 00:10

Jeffrey Harris


People also ask

How do you define stdout in python?

A built-in file object that is analogous to the interpreter's standard output stream in Python. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input.

How do I redirect standard output to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

How do you redirect in Python?

Use Python urllib Library To Get Redirection URL. request module. Define a web page URL, suppose this URL will be redirected when you send a request to it. Get the response object. Get the webserver returned response status code, if the code is 301 then it means the URL has been redirected permanently.


2 Answers

import sys

if sys.stdout.isatty():
    print "Not redirected"
else:
    sys.stderr.write("Redirected!\n")
like image 69
nosklo Avatar answered Oct 07 '22 00:10

nosklo


Actually, what you want to do here is find out if stdin and stdout are the same thing.

$ cat test.py
import os
print os.fstat(0) == os.fstat(1)
$ python test.py
True
$ python test.py > f
$ cat f
False
$ 

The longer but more traditional version of the are they the same file test just compares st_ino and st_dev. Typically, on windows these are faked up with a hash of something so that this exact design pattern will work.

like image 35
DigitalRoss Avatar answered Oct 07 '22 01:10

DigitalRoss