PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] How to check whether print() prints to terminal or file?

 September 15, 2022     file-io, printing, python, python-3.x, terminal     No comments   

Issue

Is there a way in Python 3 to check whether the following command

print('Hello')

prints to the terminal by using

python3 example.py

or prints to the file by using

python3 example.py > log.txt

...? In particular, is there a way to print different things depending on whether I use > log.txt or not?


Solution

I think you're looking for:

writing_to_tty = sys.stdout.isatty()

So...

if sys.stdout.isatty():
    print("I'm sending this to the screen")
else:
    print("I'm sending this through a pipeline or to a file")


Answered By - Thickycat
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing