如何在Python中将日期传递给脚本?

Mas*_*ben 5 python date parameter-passing

我有一个脚本删除比日期更早的图像.

当我打电话来运行脚本时,我可以将此日期作为参数传递吗?

示例:此脚本delete_images.py删除早于日期的图像(YYYY-MM-DD)

python delete_images.py 2010-12-31
Run Code Online (Sandbox Code Playgroud)

脚本(使用固定日期(xDate变量))

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 
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 17

快速但粗暴的方式是使用sys.argv.

import sys
xDate = sys.argv[1]
Run Code Online (Sandbox Code Playgroud)

更健壮,可扩展的方法是使用argparse模块:

import argparse

parser=argparse.ArgumentParser()
parser.add_argument('xDate')
args=parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

然后访问用户提供的值args.xDate而不是xDate.

使用该argparse模块,您可以在用户输入时自动获得帮助消息

delete_images.py -h
Run Code Online (Sandbox Code Playgroud)

如果用户未能提供正确的输入,它还会提供有用的错误消息.

您还可以轻松设置默认值xDate,转换xDatedatetime.date对象,并且正如他们在电视上所说,"更多,更多!".


我稍后会在你使用的脚本中看到

expDate = time.strptime(xDate, '%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)

xDate字符串转换为时间元组.你可以这样做,argparse因此args.xDate自动成为一个时间元组.例如,

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)
Run Code Online (Sandbox Code Playgroud)

当像这样运行时:

% test.py 2000-1-1
Run Code Online (Sandbox Code Playgroud)

产量

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)
Run Code Online (Sandbox Code Playgroud)

PS.无论你选择使用哪种方法(sys.argv或argparse),拉都是个好主意

expDate = time.strptime(xDate, '%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)

在...之外for-loop.由于xDate永不改变的值,您只需要计算expDate一次.