Reputation: 3587
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.
Upvotes: 4
Views: 3204
Reputation: 880927
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)
Upvotes: 3
Reputation: 11322
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)
Upvotes: 0
Reputation: 6175
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()
Upvotes: 2