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!
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.
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.
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.
import sys
if sys.stdout.isatty():
print "Not redirected"
else:
sys.stderr.write("Redirected!\n")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With