sanforyou
sanforyou

Reputation: 455

Change output logfile name inside python subprocess to make it unique

I am using python subprocess to email logfile to a user who runs python script. However each time user runs the script logfile gets overwritten. Here is the unix subprocess command I am using inside python code:

subprocess.Popen("mail -s 'logfile.log attached' -r [email protected] -a logfile.log [email protected] &> /dev/null",shell=True)

How could I make logfile name unique? Maybe incremant logfile name as logfile1.log, logfile2.log and so on?

Trick is how do I achieve this inside subprocess?

Upvotes: 0

Views: 66

Answers (2)

vladkens
vladkens

Reputation: 353

Also you can do this with datetime module:

import datetime
filename = "logfile-%s.log" % datetime.datetime.today().isoformat()
command = "mail -s '{0} attached' -r [email protected] -a {0} [email protected] &> /dev/null".format(filename)
subprocess.Popen(command, shell=True)

The name of log file will look like logfile-2015-03-13T21:37:14.927095.log.

Upvotes: 3

Heisenberg
Heisenberg

Reputation: 1508

Try using timestamp to generate a logfile name. About using that one in subprocess, command is nothing but a string. So it is as simple as

import time
fileName = "logfile." + str(time.time()) + ".log" # use your logic to generate logFile name.
command = "mail -s '%s attached' -r [email protected] -a %s [email protected] &> /dev/null" %(fileName, fileName)
subprocess.Popen(command,shell=True)

Upvotes: 1

Related Questions