This can be detected using isatty:
if sys.stdout.isatty():
# You're running in a real terminal
else:
# You're being piped or redirected
To demonstrate this in a shell:
python -c "import sys; print(sys.stdout.isatty())"should write Truepython -c "import sys; print(sys.stdout.isatty())" | catshould write False