Help me to print to screen as well as log

H

Himanshu Garg

I want that print "hello" should appear on screen as well as get saved in a log file.

How can I accomplish this?
 
S

Steven D'Aprano

I want that print "hello" should appear on screen as well as get saved
in a log file.

How can I accomplish this?

print "hello"
logfile.write("hello\n")


Does that satisfy your need? If not, please explain in more detail what
you are trying to do, what you have already tried, and what happened when
you tried it.
 
P

Peter Otten

Himanshu said:
I want that print "hello" should appear on screen as well as get saved in
a log file.

How can I accomplish this?

In Python 3 print() is a function -- you can replace it with a custom
function that invokes the original print() twice.

In both Python 3 and Python 2 you can redirect sys.stdout/stderr to a custom
object with a write() method.

If you are actually logging I suggest that you look into the logging package
which allows multiple handlers, see

http://docs.python.org/3.3/howto/logging.html

You will need to replace your print() calls with

some_logger.info(message)

or similar.
 
H

Himanshu Garg

How can I write to the same file from two different scripts opened at same time?
 
D

Dave Angel

How can I write to the same file from two different scripts opened
at same time?

Using what version of python and on what OS?

Sone OS's will open the file exclusively by default. Others will let
you stomp all over some other process' output.

Why not show us what you're trying and what happens and ask a much
more specific question?
 
M

Miki Tebeka

I want that print "hello" should appear on screen as well as get saved in a log file.
How can I accomplish this?
There are many ways to do this, here's one:

class MultiWriter(object):
def __init__(self, *writers):
self.writers = writers
self.isatty = False

def write(self, data):
for writer in self.writers:
writer.write(data)

def flush(self):
for writer in self.writers:
writer.flush()


out = open('/tmp/log.txt', 'a')
import sys
sys.stdout = MultiWriter(sys.stdout, out)
print('hello')

IMO you're better with the logging package, see http://docs.python.org/2/howto/logging.html#configuring-logging for more details.
 
H

Himanshu Garg

I have simply opened file in append mode in linux.

script 1 :

file = open("output.log", "a")
file.write()
file.flush()

script 2:

file = open("output.log", "a")
file.write()
file.flush()

It writes properly to the file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top