Python Forum
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/log
I 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


  1. You have to use the log('Your Message') everywhere, where you want to log. The print_function stays still the print_function and does not change.
  2. You're using Python 2.7, which is deprecated 2020. Upgrade to Python 3.7. In Python 2.7 print is not a function, it's a statement and the parenthesis around the arguments are recognized as a tuple and a tuple has no keyword assignment. If you need to stay with legacy Python, you should use the imports from __future__:
    from __future__ import print_function
    Then you must use everywhere print as a function

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 :-)