在Python中RW锁定Windows文件,以便每晚最多运行一个测试实例
我用 Python 编写了一个自定义测试工具(由于存在大量自定义逻辑,现有的东西不太适合)。 Windows 任务计划程序每天每小时启动一次。由于我的测试现在需要 2 个多小时才能运行,而且还在不断增长,我遇到了问题。现在我只是检查系统时间,除非hour % 3 == 0
,但我不喜欢那样。我有一个文本文件,其中包含:
# This is a comment
LatestTestedBuild = 25100
# Blank lines are skipped too
LatestTestRunStartedDate = 2011_03_26_00:01:21
# This indicates that it has not finished yet.
LatestTestRunFinishDate =
有时,当我手动启动测试时,它可能随时发生,包括 12:59:59.99 我想尽可能地消除竞争条件。我宁愿付出一些额外的努力,而不是担心事情发生的实际可能性。因此,我认为原子锁定此文本文件是最好的方法。
我使用的是 Python 2.7
、Windows Server 2008R2 Pro
和 Windows 7 Pro
。我不想安装额外的库(Python
尚未“出售”给我的同事,但我可以在本地复制一个实现所有功能的文件,只要许可证允许)。
因此,请提出一个好的、防弹的方法来解决这个问题。
I have written a custom test harness in Python (existing stuff was not a good fit due to lots of custom logic). Windows task scheduler kicks it off once per hour every day. As my tests now take more than 2 hours to run and are growing, I am running into problems. Right now I just check the system time and do nothing unless hour % 3 == 0
, but I do not like that. I have a text file that contains:
# This is a comment
LatestTestedBuild = 25100
# Blank lines are skipped too
LatestTestRunStartedDate = 2011_03_26_00:01:21
# This indicates that it has not finished yet.
LatestTestRunFinishDate =
Sometimes, when I kick off a test manually, it can happen at any time, including 12:59:59.99
I want to remove race conditions as much as possible. I would rather put some extra effort once and not worry about practical probability of something happening. So, I think locking a this text file atomically is the best approach.
I am using Python 2.7
, Windows Server 2008R2 Pro
and Windows 7 Pro
. I prefer not to install extra libraries (Python
has not been "sold" to my co-workers yet, but I could copy over a file locally that implements it all, granted that the license permits it).
So, please suggest a good, bullet-proof way to solve this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您开始运行测试时,创建一个名为 __LOCK__ 或其他名称的文件。完成后将其删除,使用 try...finally 块以确保它始终被清除。如果文件存在,请勿运行测试。如果计算机崩溃或类似情况,请手动删除该文件。我怀疑你需要比这更多的聪明才智。
你确定需要2个小时的测试吗?!我认为 2 分钟是更合理的时间,但我想如果您正在运行一些复杂的数字,您可能需要更多时间。
示例代码:
When you start running a test make a file called
__LOCK__
or something. Delete it when you finish, using a try...finally block to ensure that it always gets cleared up. Don't run the test if the file exists. If the computer crashes or similar, delete the file by hand. I doubt you need more cleverness than that.Are you sure you need 2 hours of tests?! I think 2 minutes is a more reasonable amount of time to spend, though I guess if you are running some complicated numerics you might need more.
example code: