![]() |
python file output to log file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: python file output to log file (/thread-20469.html) |
python file output to log file - Rsh - Aug-12-2019 >python logzip.py > /var/cron/logI need to capture of logzip.py output to /var/cron/log. Above shows how to do in linux pmpt. to achive this how to do in python ? RE: python file output to log file - wavic - Aug-12-2019 Print function has a file option. The default is sys.stdout but you can replace it with an open file. RE: python file output to log file - DeaD_EyE - Aug-12-2019 With pathlib: from pathlib import Path def log(msg): cron_log = Path('/var/cron/log') with cron_log.open('r+') as log_fd: print(msg, file=log_fd)Without pathlib def log(msg): with open('/var/cron/log', 'r+') as log_fd: print(msg, file=log_fd)A better solution is to use logging in Python: https://realpython.com/python-logging/#using-handlers There are different solutions. You can create a handler to log to a file, you can log to syslog and systemd. If you're not on Linux, you have lesser options. The provided example has one problem. It opens the file, write to it and then the file is closed. This happens for each message. RE: python file output to log file - Rsh - Aug-13-2019 that was a nice work of my query however i have 2 more doubts on this, 1. will this msg arguments will pass all print output to logzip.py if we add this def(msg) ? 2. In print(msg, file=log_fd)getting sysntax error for file=log_fd ! RE: python file output to log file - DeaD_EyE - Aug-13-2019
The logging module is doing a better job. You've more control about different handlers and formatting. You could also try https://github.com/Delgan/loguru The boiler-plate code has been removed :-) |