使用 io.tmpfile() 和 shell 命令,运行 通过 io.popen,在 Lua 中?
Using io.tmpfile() with shell command, ran via io.popen, in Lua?
我在 Windows 上的 Scite 中使用 Lua,但希望这是一个一般性的 Lua 问题。
假设我想将临时字符串内容写入 Lua 中的临时文件 - 我希望最终被另一个程序读取 - 我尝试使用 io.tmpfile()
:
mytmpfile = assert( io.tmpfile() )
mytmpfile:write( MYTMPTEXT )
mytmpfile:seek("set", 0) -- back to start
print("mytmpfile" .. mytmpfile .. "<<<")
mytmpfile:close()
我喜欢io.tmpfile()
,因为它在https://www.lua.org/pil/21.3.html中有注明:
The tmpfile function returns a handle for a temporary file, open in read/write mode. That file is automatically removed (deleted) when your program ends.
但是,当我尝试打印 mytmpfile
时,我得到:
C:\Users\ME/sciteLuaFunctions.lua:956: attempt to concatenate a FILE* value (global 'mytmpfile')
>Lua: error occurred while processing command
我在这里得到了解释 Re: path for io.tmpfile() ?:
how do I get the path used to generate the temp file created by io.tmpfile()
你不能。 tmpfile 的全部要点是给你一个文件句柄而不
给你文件名以避免竞争条件。
确实,在某些 OSes 上,文件没有名称。
所以,我不可能在命令行中使用 tmpfile 的文件名,应该是 OS 的 运行,如:
f = io.popen("python myprog.py " .. mytmpfile)
所以我的问题是:
- 是否可以将此 tmpfile 文件句柄指定为外部 运行 program/script 的输入参数,例如
io.popen
- 而不是使用(不存在的) tmpfile 文件名?
- 如果以上不可能,那么在 Lua 中打开临时文件的下一个最佳选择是什么(就不必维护它而言,即不必记住删除文件)?
您可以使用 os.tmpname
获取临时文件名。
local n = os.tmpname()
local f = io.open(n, 'w+b')
f:write(....)
f:close()
os.remove(n)
如果您的目的是将一些数据发送到 python 脚本,您也可以在 popen 中使用 'w' 模式。
--lua
local f = io.popen(prog, 'w')
f:write(....)
#python
import sys
data = sys.stdin.readline()
我在 Windows 上的 Scite 中使用 Lua,但希望这是一个一般性的 Lua 问题。
假设我想将临时字符串内容写入 Lua 中的临时文件 - 我希望最终被另一个程序读取 - 我尝试使用 io.tmpfile()
:
mytmpfile = assert( io.tmpfile() )
mytmpfile:write( MYTMPTEXT )
mytmpfile:seek("set", 0) -- back to start
print("mytmpfile" .. mytmpfile .. "<<<")
mytmpfile:close()
我喜欢io.tmpfile()
,因为它在https://www.lua.org/pil/21.3.html中有注明:
The tmpfile function returns a handle for a temporary file, open in read/write mode. That file is automatically removed (deleted) when your program ends.
但是,当我尝试打印 mytmpfile
时,我得到:
C:\Users\ME/sciteLuaFunctions.lua:956: attempt to concatenate a FILE* value (global 'mytmpfile')
>Lua: error occurred while processing command
我在这里得到了解释 Re: path for io.tmpfile() ?:
how do I get the path used to generate the temp file created by io.tmpfile()
你不能。 tmpfile 的全部要点是给你一个文件句柄而不 给你文件名以避免竞争条件。
确实,在某些 OSes 上,文件没有名称。
所以,我不可能在命令行中使用 tmpfile 的文件名,应该是 OS 的 运行,如:
f = io.popen("python myprog.py " .. mytmpfile)
所以我的问题是:
- 是否可以将此 tmpfile 文件句柄指定为外部 运行 program/script 的输入参数,例如
io.popen
- 而不是使用(不存在的) tmpfile 文件名? - 如果以上不可能,那么在 Lua 中打开临时文件的下一个最佳选择是什么(就不必维护它而言,即不必记住删除文件)?
您可以使用 os.tmpname
获取临时文件名。
local n = os.tmpname()
local f = io.open(n, 'w+b')
f:write(....)
f:close()
os.remove(n)
如果您的目的是将一些数据发送到 python 脚本,您也可以在 popen 中使用 'w' 模式。
--lua
local f = io.popen(prog, 'w')
f:write(....)
#python
import sys
data = sys.stdin.readline()