Question

I am executing a program with a combination of different parameters. I need to keep track of exactly which parameters were supplied with the program at command line. I am maintaining a log file where I need to store these issued commands alogwith summary of the result.

for example, I may issue following commands at different times.

$python myprog.py -i input.txt -o output.txt -x 2 -y 3 -z 9
$python myprog.py  input.txt -o output.txt -x 2  -z 9
$python myprog.py -i input.txt -o output.txt -x 2 -y 3 
$python myprog.py -i input.txt -o output.txt  -z 9

How can I store these commands into my log file?

I am doing this because I might need to re-execute the same program with exact same options.

Was it helpful?

Solution

You can use the module sys to get all arguments as a list, argv. To log them to a text file you can use this piece of code:

import sys
logfile = open("logfile.txt", "w")
logfile.write(" ".join(sys.argv))
logfile.close()

OTHER TIPS

You could use the logging module:

import logging
import sys
logger = logging.getLogger(__name__)

if __name__ == '__main__':
    logging.basicConfig(filename = '/tmp/command.log', level = logging.INFO,
                        format = '%(asctime)s %(message)s',
                        datefmt = '%Y-%m-%d %H:%M:%S')

    logger.info(sys.argv)

You can capture the arguments inside your program from sys.argv, and append them to a log file.

import datetime
import sys
if __name__ == '__main__':
    now = datetime.datetime.now().ctime()
    with open('logfile', 'a') as log:
        log.write("Invoked at %s with args: %s\n" % (now, sys.argv) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top