我正在尝试有效的用户输入。我有多种类型的有效日期,而且只有一个空白。可能有一种简单的方法来检查这个,但我无法弄明白。
def check_input(i):
valids = ['%Y-%m-%d', '%Y%M', '']
while True:
try:
date = strptime(i, valids)
except ValueError as e:
print 'Could not parse: {}'. format(e)
else:
return True
我认为我不能将列表传递给strptime对象。它返回TypeError:unhashable type:'list'。
以下是脚本的片段
def parse_arguments():
parser = argparse.ArgumentParser(description='API Statistics')
parser.add_argument('-c', '--company', help='Company name')
parser.add_argument('-d', '--download', help='Download file', action='store_true')
return parser.parse_args()
def list_cmds(company):
for num, cmd in enumerate(company._cmds):
print '{}: {}'.format(num, cmd)
def get_cmd_dict(company):
return dict(enumerate(company._cmds))
def run_cmd(i, cmd, **kwargs):
return getattr(i, get_cmd_dict(i)[int(cmd)])(**kwargs)
def writer(data, file):
with open(file, 'w') as f:
f.write(data)
def get_func_args(f):
ins = inspect.getargspec(f).args
ins.remove('self')
return ins
def check_input(i):
valids = ['%Y-%m-%d', '%Y%M', '']
while True:
try:
date = strptime(i, valids)
except ValueError as e:
print 'Could not parse: {}'. format(e)
else:
return True
def main():
args = parse_arguments()
if args.company == 'parklogic':
i = PlAPI(11111, 'asdf', 'program', debug=False)
pl_cmds = get_cmd_dict(i)
print 'please select a command'
print '-----------------------'
list_cmds(PlAPI)
user_cmd = raw_input('Number: ')
print ''
cmd_args = get_func_args(getattr(i, pl_cmds[int(user_cmd)]))
users_args = {}
format_mapper = {0: 'YYYY-MM-DD',
1: 'YYYY-MM-DD',
2: 'YYYY-MM-DD',
3: 'YYYY-MM-DD',
4: 'YYYYMM',
5: 'YYYY-MM-DD',
6: 'YYYY-MM-DD HH:mm:ss',
7: 'YYYY-MM-DD',
8: 'YYYY-MM-DD'}
for arg in cmd_args:
user_input = raw_input('Enter {} as {} or leave blank: '.format(
arg, format_mapper[int(user_cmd)]))
if check_input(user_input):
users_args[arg] = user_input
resp = run_cmd(i, user_cmd, **users_args)
if args.download:
writer(resp.read(), '{}.csv'.format(pl_cmds[int(user_cmd)]))
else:
print resp.read()
if __name__ == '__main__':
main()
答案 0 :(得分:1)
def check_input(i):
valids = ['%Y-%m-%d', '%Y%M', '']
for valid in valids
try:
return strptime(i, valid)
except ValueError as e:
pass
return False