【问题标题】:Execute function while value of var is between 2 thresholds在 var 的值介于 2 个阈值之间时执行函数
【发布时间】:2019-09-30 03:34:39
【问题描述】:

我有一个脚本可以清理文件系统中的日志。我需要我的代码在一个带有目录列表的 for 中执行 2 个函数(clean、checksize)。 我的问题是我无法在我定义的两个阈值之间进行迭代。

这是我的代码:

count = 0
success = False

tmin = 90
tmax = 95

if (size > tmax):
    for directorio in directorios:
        count += 1
        if success:
            break
        for directorio in zip(*directorios[count - 1]):
            ruta = directorio[1]+'/builds/'
            if os.path.exists(ruta):
                flushdir(ruta)
                size = int(get_path_perc(path))
                print ("Has been removed: ", ruta)
            if (size <= tmin):
                success = True
                break

Flushdir是删除目录的函数,size是检查空闲空间的函数。 实际结果是只执行第一个threshold(tmax)中的函数,而不是tmin中的函数,我需要函数在两个阈值中执行..

提前致谢。

【问题讨论】:

  • 明确地说,您想删除一个大小在 tmin 和 tmax(包括两者)之间的目录,对吗?还有,首先 size 的值是多少?
  • 大小的值可以是任何人。如果值超过 tmax,则代码必须执行。当值小于 tmax 但大于 tmin 时,必须执行。当 size 小于 tmin 时,脚本必须完成。
  • 请举例说明directorios 的可能值,我假设它是一个目录名称列表但不能确定,因为它用作zip 参数列表,所以很混乱。作为一个起点,我建议放弃 for 循环并改用 while size &gt; tmin:,我觉得它可以大大简化您的代码。
  • @Tryph 可能的值可以是:例如 /home/user/。
  • 仍然不确定这应该做什么。据我了解,当计数高于 tmax 时,它应该开始“清理”,并清理直到计数低于 tmin,对吧?如果计数在 tmin 和 tmax 之间,则不应开始清理(但如果已在清理,则继续)

标签: python python-3.5


【解决方案1】:

不是基于多个for 循环、变量设置和条件break 来做复杂的事情,难道不能用一个while 做更简单的事情吗?

tmin = 90
tmax = 95

size = int(get_path_perc(path))
if size > tmax:  # cleaning process needed
    index = 0  # starts at first directory...
    while size > tmin:  # ... until size is lower than `tmin`
        ruta = os.join(zip(*directorios[index])[1], 'builds')
        if os.path.exists(ruta):
            flushdir(ruta)
            size = int(get_path_perc(path))
            print ("Has been removed: ", ruta)
        index += 1  # consider next directory in next iteration

这未经测试,这个zip 调用directorios 似乎很可疑,但不知道directorios 中的内容,很难做得更好......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2017-02-10
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多