gpt4 book ai didi

file - 写入操作后数据未出现在日志文件中

转载 作者:行者123 更新时间:2023-12-01 13:40:58 25 4
gpt4 key购买 nike

我有以下代码:

time = os.date("*t")
data = io.open("test.txt", "a")

function applicationWatcher(appName, eventType, appObject)
if (eventType == hs.application.watcher.launched) then
data:write("" .. appName .. " launched at ".. ("%02d:%02d:%02d:%02d:%02d:%02d"):format(time.day, time.month, time.year, time.hour, time.min, time.sec))
end
end

local appWatcher = hs.application.watcher.new(applicationWatcher)
appWatcher:start()

当您在 macOS 上启动应用程序时,会看到此代码。我希望程序在文件中记录时间、日期和应用程序的名称,以便我可以查看启动了哪些应用程序以及启动时间。

似乎没有任何内容登录到我的文本文件中。为什么?

最佳答案

文件 I/O 是 buffered .这意味着数据并不总是立即写入文件,而是保存在内存中直到缓冲区已满,因此可以批量写入数据。

简单的解决方法是简单地使用 file:flush立即将缓冲区中的数据推送到文件中。

data:write('name and timestamp')
data:flush()

更高级的解决方案是使用 file:setvbuf设置适当的 mode 和缓冲区 size:

file:setvbuf (mode [, size])

Sets the buffering mode for an output file. There are three available modes:

  • "no": no buffering; the result of any output operation appears immediately.
  • "full": full buffering; output operation is performed only when the buffer is full or when you explicitly flush the file (see io.flush).
  • "line": line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device).

For the last two cases, size specifies the size of the buffer, in bytes. The default is an appropriate size.

您可能想要的是 'line' 缓冲,因为无论如何您都应该在字符串的末尾添加一个换行符 ('\n'),否则您的日志文件将很难阅读。

local data = io.open("test.txt", "a")
data:setvbuf('line')

关于file - 写入操作后数据未出现在日志文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com