How to pass a date to a script in Python?

I have a script to delete images older than date.

Can I pass this date as an argument when called to run the script?

Example: this script delete_images.py deletes images older than the date (YYYY-MM-DD)

 python delete_images.py 2010-12-31 

Script (works with 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 
+4
source share
4 answers

A quick but rough way is to use sys.argv .

 import sys xDate = sys.argv[1] 

A more robust, extensible way is to use the argparse module:

 import argparse parser=argparse.ArgumentParser() parser.add_argument('xDate') args=parser.parse_args() 

Then, to access the value provided by the user, use args.xDate instead of xDate .

Using the argparse module, you automatically receive a free help message when a user types

 delete_images.py -h 

It also gives a useful error message if the user cannot provide the correct entries.

You can also easily set the default value for xDate , convert xDate to a datetime.date object and, as they say on TV, "much, much more!".


Below you see the script you are using

 expDate = time.strptime(xDate, '%Y-%m-%d') 

to convert the xDate string to a temporary tuple. You can do this with argparse , so args.xDate will be a time tuple automatically. For instance,

 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) 

upon startup as follows:

 % test.py 2000-1-1 

gives

 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. Whichever method you choose (sys.argv or argparse), it would be nice to pull

 expDate = time.strptime(xDate, '%Y-%m-%d') 

out of for-loop . Since the value of xDate never changes, you only need to calculate expDate once.

+16
source

Command line options can be accessed through the sys.argv list. Therefore you can just use

 xDate = sys.argv[1] 

( sys.argv[0] is the name of the current script.)

+2
source

A bit more polish unutbu 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) 
+1
source

you can use runtime arguments for this approach. See the following link: http://www.faqs.org/docs/diveintopython/kgp_commandline.html

0
source

Source: https://habr.com/ru/post/1382092/


All Articles