redirect prints to log file

Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of print statements before running a command using os.system() say something like,

print "running command",cmd
os.system(cmd)

Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all print statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips.


Asked by: Emma170 | Posted: 27-01-2022






Answer 1

Python lets you capture and assign sys.stdout - as mentioned - to do this:

import sys
old_stdout = sys.stdout

log_file = open("message.log","w")

sys.stdout = log_file

print "this will be written to message.log"

sys.stdout = old_stdout

log_file.close()

Answered by: Chelsea475 | Posted: 28-02-2022



Answer 2

You should take a look at python logging module


EDIT: Sample code:

import logging

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
                        format="%(asctime)-15s %(levelname)-8s %(message)s")
    logging.info("hello")

Produce a file named "logfile" with content:

2012-10-18 06:40:03,582 INFO     hello

Answered by: Lenny518 | Posted: 28-02-2022



Answer 3

  • Next time, you'll be happier if instead of using print statements at all you use the logging module from the start. It provides the control you want and you can have it write to stdout while that's still where you want it.

  • Many people here have suggested redirecting stdout. This is an ugly solution. It mutates a global and—what's worse—it mutates it for this one module's use. I would sooner make a regex that changes all print foo to print >>my_file, foo and set my_file to either stdout or an actual file of my choosing.

    • If you have any other parts of the application that actually depend on writing to stdout (or ever will in the future but you don't know it yet), this breaks them. Even if you don't, it makes reading your module look like it does one thing when it actually does another if you missed one little line up top.
    • Chevron print is pretty ugly, but not nearly as ugly as temporarily changing sys.stdout for the process.
    • Very technically speaking, a regex replacement isn't capable of doing this right (for example, it could make false positives if you are inside of a multiline string literal). However, it's apt to work, just keep an eye on it.
  • os.system is virtually always inferior to using the subprocess module. The latter needn't invoke the shell, doesn't pass signals in a way that usually is unwanted, and can be used in a non-blocking manner.

Answered by: Brooke717 | Posted: 28-02-2022



Answer 4

You can create a log file and prepare it for writing. Then create a function:

def write_log(*args):
    line = ' '.join([str(a) for a in args])
    log_file.write(line+'\n')
    print(line)

and then replace your print() function name with write_log()

Answered by: Emily146 | Posted: 28-02-2022



Answer 5

A simple way to redirect stdout and stderr using the logging module is here: How do I duplicate sys.stdout to a log file in python?

Answered by: Catherine957 | Posted: 28-02-2022



Answer 6

You can redirect replace sys.stdout with any object which has same interface as sys.stdout, in that object's write you can print to terminal and to file too. e.g. see this recipe http://code.activestate.com/recipes/119404-print-hook/

Answered by: Aida448 | Posted: 28-02-2022



Answer 7

there are many way to write output into the '.log' file

Logging is a means of tracking events it happen when some file runs. Is also indicate that certain events have occurred.

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This is debug message')
logging.info('This is information message')
logging.warning('This is warning message')
logging.error('This is warning message')

another method to use to reduce all that thing sinple what ever you print to the console that all will be saved to the ''log'' file

python abc.py > abc.log

by using this method you can write everything to the log file

Answered by: Aida972 | Posted: 28-02-2022



Answer 8

Putting your own file-like in sys.stdout will let you capture the text output via print.

Answered by: Sydney974 | Posted: 28-02-2022



Answer 9

Just a note about append vs write mode. Change filemode to "w" if you would like it to replace log file. I also had to comment out the stream. Then using logging.info() was outputting to file specified.

if __name__ == '__main__':
    LOG_FORMAT = '%(asctime)s:%(levelname)s ==> %(message)s'
    logging.basicConfig(
        level=logging.INFO,
        filename="logfile",
        filemode="w",
        format=LOG_FORMAT
        #stream=sys.stdout
    )

Answered by: Leonardo197 | Posted: 28-02-2022



Answer 10

def log(txt):
    f = open(__file__ + '.log', "a")
    f.write(txt + '\r\n')
    f.close()

Usage:

log('Hello World!')

Example:

python3 helloworld.py

Will append to file ./helloworld.py.log. If file doesn't exist, it will create it.

Answered by: Adelaide454 | Posted: 28-02-2022



Similar questions

python - How to redirect prints to log file on nohup

nohup python3 main.py > log.output & So with this, I am getting some output by my framework but my individual print statements are not being logged to log.output. Is there anyway to fix this? Output under nohup nohup: ignoring input * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * De...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


python - Pylons redirect to 404 error page

What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you!


python - Error using redirect in pylons

Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simplefor...


Python CGI script - redirect doesn't always work

I'm writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then displays one or another version of its own page depending on what it just did. E.g. if you add a comment, it reloads the "item" version of the page rather than the "list of all items" view, incorporating the new comment. There are several places in the program where it's supposed to reload itself. In o...


python - how to redirect to particular url on 404

@error(404) def error404(error): return 'Nothing here, sorry' This is the way to response 404 in bottle framework. But On 404 I want to redirect to particular url say http://abc.com/. Is it possible?


python - how to redirect form after submit

I've a form, where users select the years and gender, then they click on submit. With these values I'm calculating the numbers, drawing some pictures, etc. Everything fine so far. What I would like to do is open these pictures and data into a pdf file, with the help of documentation. The thing is that I'm not able to redire...


python - Django redirect the right way?

I have a similar question to this - Conditional login redirect in Django But I couldn't understand how to achieve the result from answers there. I am relatively new to django. I reused this code from somewhere, which redirects the user to login page. But after login I always get to the start/ho...


python - Check secure OpenID redirect?

The process for openid login for my server redirects to google, for example, then google redirects back to a page with parameters in the parameter string. how do I verify this really came from google?


bash - Redirect command to input of another in Python

I would like to replicate this in python: gvimdiff <(hg cat file.txt) file.txt (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" Getting to the python part... # hg...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done bef...


python - Django: Redirect to previous page after login

I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I ...


How to redirect the output of .exe to a file in python?

In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?


python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


How to redirect stderr in Python? Via Python C API?

This is a combination of my two recent questions: [1] Python instance method in C [2] How to redirect stderr in Python? I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...


How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried: import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead. Ho...


linux - Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write: exec 2>&1 exec someprog And the stderr output of someprog would be redirected to stdout. Is there any way to do a similar thing using python's os.exec* functions? This doesn't have to be portable, just work on Linux.






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top