写入操作后数据未出现在日志文件中
Data not appearing in log file after write operation
我有以下代码:
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')
我有以下代码:
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')