Search notes:

Python: sys.stdin / sys.stdout / sys.stderr

Writing to stdout or to a file

The following example writes to a file if the script was started with an argument (sys.argv[1]) or to stdout otherwise.
import sys

if len(sys.argv) > 1:
   print("Writing to file " + sys.argv[1])

   f_ = open(sys.argv[1], 'w')

else:

   f_ = sys.stdout

f_.write('Line one\n')
f_.write('Line two\n')
f_.write('Line three')

if len(sys.argv) > 1:
   f_.close()
Github repository about-python, path: /standard-library/sys/stdout_or_file.py
The script should be called with either of the two variants:
$ python stdout_or_file.py
$ python stdout_or_file.py out.txt

See also

stdin, stdout and stderr

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759396511, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/standard-library/sys/stdin-stdout-stderr/index(65): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78