随后如何调用python函数调用

时间:2019-07-30 16:04:08

标签: python

我有一个python函数,它在第一次调用时按预期工作。 我添加另一个电话后,它立即出现错误“ IndexError:列表索引超出范围”

import os
import re
import glob

LDIR="/data/reports/get-snapshots/labs"
PDIR="/data/reports/get-snapsnots/prod"


def get_latest_snap_files(path, *paths):
    snap_path=os.path.join(path, *paths)
    snap_file=sorted(glob.iglob(snap_path), key=os.path.getctime, reverse=True)
    return snap_file[0]

def main():
    l=get_latest_snap_files(LDIR, '*')
    print(l)
    p=get_latest_snap_files(PDIR, '*')
    print(p)
main()

$python h.py
/data/reports/get-snapshots/labs/labs.snapshot.2019-05-25_184501-out.sorted.log

Traceback (most recent call last):
  File "h.py", line 24, in <module>
    main()
  File "h.py", line 22, in main
    p=get_latest_snap_files(PDIR, '*')
  File "h.py", line 16, in get_latest_snap_files
    print(snap_file[0])
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

根据@Chris_Rands对您答案的评论,snap_file有时可能为空。

您应该检查并在发生这种情况时返回None

import os
import re
import glob

LDIR="/data/reports/get-snapshots/labs"
PDIR="/data/reports/get-snapsnots/prod"


def get_latest_snap_files(path, *paths):
    snap_path=os.path.join(path, *paths)
    snap_file=sorted(glob.iglob(snap_path), key=os.path.getctime, reverse=True)
    return None if len(snap_file) == 0 else snap_file[0]

def main():
    l=get_latest_snap_files(LDIR, '*')
    print(l)
    p=get_latest_snap_files(PDIR, '*')
    print(p)
main()