【发布时间】:2021-05-03 21:56:07
【问题描述】:
试图清理它以将时间作为参数通过 argparse 而不是 sys.这个想法是将时间参数作为输入并再次搜索存储桶,转换它们并返回匹配项。它适用于 sys.argv 值,但这显然是有限的。尝试使用 argparse 选项进行重构。
你会看到的
start_time = sys.argv[3] end_time = sys.argv[5] 是硬编码的
import argparse
import logging
import os
import sys
import re
import time
"""take CLI parameters and search against bucket, converts them and return matching dirs"""
FILE = 'bucket'
TIME_FORMAT = "%m-%d-%Y-%H:%M:%S"
def get_file():
"""Get to dir, fetch resources"""
s3 = resource('s3')
bucket = s3.Bucket(FILE)
index = sys.argv[2]
objects = bucket.objects.filter(Prefix=index)
return objects
def convert_index():
"""conversion of the epoch filenames output
"""
dir_files = get_file()
for file in dir_files:
output = file.key # file is a class type
if 'db_' in output:
output_dir = output.split('/')
times = output_dir # [1] is index name only
start_time = sys.argv[3]
end_time = sys.argv[5]
fields = times[2].split('_')
try:
start = convert_epoch(fields[1]) # first time field
end = convert_epoch(fields[2]) # second time field
if start.startswith(start_time) or end.startswith(start_time) == start_time:
print("{}\t\t is {}_{}".format(output, start, end))
logging.basicConfig(level=logging.INFO, filename='logfile.log', format='%(asctime)s - \
%(levelname)s - %(message)s')
elif end.startswith(end_time) or end.startswith(end_time) == end_time:
print("{}\t\t\t is {}_{}".format(output, start, end))
except ValueError as ve:
logging.info("did not convert due to {}".format(ve))
def convert_epoch(input_epoch):
"""takes epoch value and converts to human readable
time.strftime("%m-%d-%Y_%H-%M-%S", time.localtime(1442530758))
'09-17-2019_15-59-18'
"""
converted_epoch_value = time.strftime(TIME_FORMAT, time.localtime(int(input_epoch)))
return converted_epoch_value
def main():
parser: ArgumentParser = argparse.ArgumentParser(
description="""Supply the directory you want to search files for. Give earliest and latest time to query bucket for
usage: format_files.py [-h] [-e --earliest] [-l --latest]""")
parser.add_argument('-i', '--index', required=False, help='index name directory to query for ex:\n'
'format_files.py -i folder/folder')
parser.add_argument('-s', '--start_time', required=False, help='queries from start time (not necessarily earliest time)')
parser.add_argument('-e', '--end_time', required=False, help='queries data until end time (not necessarily latest time)')
args = parser.parse_args()
if len(sys.argv) < 2:
sys.exit(parser.description)
if args.index:
convert_index()
if __name__ == "__main__":
main()
在 if start.startswith(start_time) 或 end.startswith(start_time) == start_time 中遇到问题: 尝试传递 argparse 选项时的行
感谢任何见解
【问题讨论】:
-
start_time=args.start_time等 -
清理你的代码。如果您已经使用
argparse解析输入,则不需要使用sys.argv。
标签: python python-3.x time argparse