How can I pass a date to a script in Python?
Solution 1
The quick but crude way is to use sys.argv
.
import sys
xDate = sys.argv[1]
A more robust, extendable way is to use the argparse module:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('xDate')
args=parser.parse_args()
Then to access the user-supplied value you'd use args.xDate
instead of xDate
.
Using the argparse
module you automatically get a help message for free when a user types
delete_images.py -h
It also gives a helpful error message if the user fails to supply the proper inputs.
You can also easily set up a default value for xDate
, convert xDate
into a datetime.date
object, and, as they say on TV, "much, much more!".
I see later in you script you use
expDate = time.strptime(xDate, '%Y-%m-%d')
to convert the xDate
string into a time tuple. You could do this with argparse
so args.xDate
is automatically a time tuple. For example,
import argparse
import time
def mkdate(datestr):
return time.strptime(datestr, '%Y-%m-%d')
parser=argparse.ArgumentParser()
parser.add_argument('xDate',type=mkdate)
args=parser.parse_args()
print(args.xDate)
when run like this:
% test.py 2000-1-1
yields
time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
PS. Whatever method you choose to use (sys.argv or argparse), it would be a good idea to pull
expDate = time.strptime(xDate, '%Y-%m-%d')
outside of the for-loop
. Since the value of xDate
never changes, you only need to compute expDate
once.
Solution 2
Little bit more polish to unutbu's answer:
import argparse
import time
def mkdate(datestr):
try:
return time.strptime(datestr, '%Y-%m-%d')
except ValueError:
raise argparse.ArgumentTypeError(datestr + ' is not a proper date string')
parser=argparse.ArgumentParser()
parser.add_argument('xDate',type=mkdate)
args=parser.parse_args()
print(args.xDate)
Solution 3
The command line options can be accessed via the list sys.argv
. So you can simply use
xDate = sys.argv[1]
(sys.argv[0]
is the name of the current script.)
AurumAustralis
Updated on July 09, 2022Comments
-
AurumAustralis almost 2 years
I have a script for deleting images older than a date.
Can I pass this date as an argument when I call to run the script?
Example: This script
delete_images.py
deletes images older than a date (YYYY-MM-DD)python delete_images.py 2010-12-31
Script (works with a fixed date (xDate variable))
import os, glob, time root = '/home/master/files/' # one specific folder #root = 'D:\\Vacation\\*' # or all the subfolders too # expiration date in the format YYYY-MM-DD ### I have to pass the date from the script ### xDate = '2010-12-31' print '-'*50 for folder in glob.glob(root): print folder # here .jpg image files, but could be .txt files or whatever for image in glob.glob(folder + '/*.jpg'): # retrieves the stats for the current jpeg image file # the tuple element at index 8 is the last-modified-date stats = os.stat(image) # put the two dates into matching format lastmodDate = time.localtime(stats[8]) expDate = time.strptime(xDate, '%Y-%m-%d') print image, time.strftime("%m/%d/%y", lastmodDate) # check if image-last-modified-date is outdated if expDate > lastmodDate: try: print 'Removing', image, time.strftime("(older than %m/%d/%y)", expDate) os.remove(image) # commented out for testing except OSError: print 'Could not remove', image