del语句是否打开内存?

2024-05-09 12:56:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个python脚本,在晚上睡觉时备份我的文件。该程序设计为在计算机打开时运行,并在备份完成后自动关闭计算机。我的代码如下所示:

from datetime import datetime
from os import system
from backup import backup

while True:
    today = datetime.now()

    # Perform backups on Monday at 3:00am.
    if today.weekday() == 0 and today.hour == 3:
        print('Starting backups...')

        # Perform backups.
        backup("C:\\Users\\Jeff Moorhead\\Desktop", "E:\\")
        backup("C:\\Users\\Jeff Moorhead\\Desktop", "F:\\")
        backup("C:\\Users\\Jeff Moorhead\\OneDrive\\Documents", "E:\\")
        backup("C:\\Users\\Jeff Moorhead\\OneDrive\\Documents", "F:\\")

        # Shutdown computer after backups finish.
        system('shutdown /s /t 10')
        break

    else:
        del today
        continue

备份功能来自另一个文件,我编写该文件是为了根据具体情况执行更多自定义备份。这段代码运行得非常好,但是我想知道del语句

del today

这是非常必要的。我认为这可以防止我的内存被数千个datetime对象填满,但后来我看到Python使用垃圾收集,类似于Java。此外,today变量是否会自动替换为while循环中的每个过程?我知道这个程序按照del语句的预期工作,但是如果它是不必要的,那么我想去掉它,如果只是为了简洁!它对记忆的实际影响是什么


Tags: 文件fromimporttodaydatetime计算机备份system
1条回答
网友
1楼 · 发布于 2024-05-09 12:56:23

I put it in thinking that it would prevent my memory from getting filled up by thousands of datetime objects

del语句不是必需的,您只需删除该块即可。Python将自动从这些局部变量中释放空间

... but then I read that Python uses garbage collection, similar to Java.

上面的陈述是错误的:这与垃圾收集器无关,垃圾收集器的存在是为了分解循环引用。在CPython中,当对象引用计数减少到零时,内存被释放,即使禁用了垃圾收集器,也会发生这种情况

Further, does the today variable automatically get replaced with each pass through the while loop? I know that the program works as intended with the del statement, but if it is unnecessary, then I would like to get rid of it if only for the sake of brevity! What are it's actual effects on memory?

循环的每次迭代都会创建一个新的datetime对象。 作用域中的today名称将反弹到新创建的datetime实例。旧的datetime实例将被删除,因为其上不存在引用(因为将名称today重新定位到其他对象后,唯一现有的引用将丢失)。我再次强调,这只是ref计数,与^{}无关

另一方面,您的程序将在这个while循环中忙循环并消耗整个CPU。应该考虑将一个调用{{CD5}}添加到循环中,这样进程将保持空闲。或者,更好的方法是使用^{}定期运行任务

相关问题 更多 >