【问题标题】:Why is os.path.getmtime() always running twice? It does not make any sense为什么 os.path.getmtime() 总是运行两次?这没有任何意义
【发布时间】:2020-04-02 10:35:21
【问题描述】:

代码如下:

import os
import asyncio
async def func_placing_sell_orders():
    prev_final_stocks_list_state = os.path.getmtime('stock_data//final_stocks_list.json')
    print('i run once')
    while True:
        if (prev_final_stocks_list_state != os.path.getmtime('stock_data//final_stocks_list.json')):
            prev_final_stocks_list_state = os.path.getmtime('stock_data//final_stocks_list.json')
            print('here')

asyncio.get_event_loop().run_until_complete(func_placing_sell_orders())

简化版:

import os
def simple():
    state = os.path.getmtime('file.json')
    print('i run once')
    while True:
        if (state != os.path.getmtime('file.json')):
            state = os.path.getmtime('file.json')
            print('here')

simple()

这是打印出来的:

i run once
here
here

这里,每次保存文件时都会打印两次。我跑来检查以前和当前修改时间之间的时间,它总是不同的,这意味着每次保存它应该只运行一次。

这太基本了,我不明白为什么我会得到这个结果。请发送帮助

【问题讨论】:

  • 我有点惊讶它 only 运行了两次,因为它在无限循环中被调用......我不明白你为什么使用 async函数,你的函数中没有任何异步。
  • 不是响应,是代码与报错不符的注释,表示求助请求不连贯。此外,示例代码根本无法运行。在 10% 的相关信息存在而 90% 的信息缺失时协助解决问题是很困难的。
  • @the_begging_beginner 尽量礼貌一点。 是寻求帮助的人。
  • 其他东西正在修改文件。当我如图所示运行您的简化示例时(将while True 替换为for _ in range(10),我看不到'here' 打印根本

标签: python asynchronous last-modified


【解决方案1】:

如果文件足够大,第一个“这里”可能是文件仍在写入编辑时,最后一个“这里”是在保存完成之后。此外,如果您使用 open("file", "w") 之类的东西或类似的东西来编写编辑,文件将首先是干净的(第一个“这里”),然后用新数据编辑(第二个“这里”)

您可以使用简单的计时器忽略过快的报告 (

lastEdit = time.time()
while True:
    if (state != os.path.getmtime('file.json')):
        state = os.path.getmtime('file.json')
        if time.time()-lastEdit > 1: 
            print('here')
        lastEdit = time.time()

【讨论】:

  • 这是正确答案。我不知道文件大小会改变这样的行为。有没有办法缓解它(即确保只有一个通过)?
  • 添加了可能的解决方案
猜你喜欢
  • 1970-01-01
  • 2013-02-18
  • 2022-08-03
  • 2018-09-12
  • 1970-01-01
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多