Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python output on file and terminal

There are times when I want my program to write something on the terminal for immediate inspection and on a file for later use, so I write something like:

print "output"
file.write("output")   #the same output as the previous line

Is it possible, with python 2.6 or 7, to do it in another, maybe smarter, way?

like image 559
mattiav27 Avatar asked Mar 07 '14 13:03

mattiav27


People also ask

How do you write output to a file in Terminal?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do I print Python output in terminal?

To print strings to console or echo some data to console output, use Python inbuilt print() function. print() function can take different type of values as argument(s), like string, integer, float, etc., or object of a class type.

How do you get input and output in Python?

Input-Output and Files in Python. Using Python input/output functions, we can get the input from the user during run-time or from external sources like text file etc. If we want to write a huge number of data into a file then we can achieve it using Python file output methods.

How do I run a python script in terminal?

The command to execute a Python file is "python" or "python3" depending on how Python is installed on your computer. We type that along with the name of the file to be executed. As we see in the output above, our script prints today's date in the terminal.

How to print output to a file in Python?

Use the contextlib.redirect_stdout () Function to Print Output to a File in Python There is one more kind of task in file handling that can be done using python i.e redirecting output to an external file. Basically, a standard output can be printed to a file that is chosen by the user itself. There are many ways to carry this out.

How to write data into a file in Python?

In order to write the data into a file, we need to open the file in write mode. Every time when we open the file, as a good practice we need to ensure to close the file, In python, we can use close () function to close the file.


1 Answers

You could wrap that into a function:

>>> def fprint(output):
...    print output
...    with open("somefile.txt", "a") as f:
...        f.write("{}\n".format(output))

If this is logging information, you should look into the logging module. Using the logging module you can easily configure and control multiple destinations for the logging events.

Example from the logging cookbook:

import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.'

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.') # Won't print, file only
logger1.info('How quickly daft jumping zebras vex.') # Printed and to file
logger2.warning('Jail zesty vixen who grabbed pay from quack.') # Printed and to file
logger2.error('The five boxing wizards jump quickly.') # Printed and to file.

The above example will write all messages with a logging level of logging.DEBUG or higher to a file called /temp/myapp.log. Messages with level logging.INFO are printed to sys.stderr. I highly advocate the use of this module for any logging purposes above simple debug prints.

EDIT: Had the wrong example!

like image 200
msvalkon Avatar answered Nov 15 '22 07:11

msvalkon