sdbbs
sdbbs

Reputation: 5394

Using io.tmpfile() with shell command, ran via io.popen, in Lua?

I'm using Lua in Scite on Windows, but hopefully this is a general Lua question.

Let's say I want to write a temporary string content to a temporary file in Lua - which I want to be eventually read by another program, - and I tried using io.tmpfile():

mytmpfile = assert( io.tmpfile() )
mytmpfile:write( MYTMPTEXT )
mytmpfile:seek("set", 0) -- back to start
print("mytmpfile" .. mytmpfile .. "<<<")
mytmpfile:close()

I like io.tmpfile() because it is noted in 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.

However, when I try to print mytmpfile, I get:

C:\Users\ME/sciteLuaFunctions.lua:956: attempt to concatenate a FILE* value (global 'mytmpfile')
>Lua: error occurred while processing command

I got the explanation for that here Re: path for io.tmpfile() ?:

how do I get the path used to generate the temp file created by io.tmpfile()

You can't. The whole point of tmpfile is to give you a file handle without giving you the file name to avoid race conditions.

And indeed, on some OSes, the file has no name.

So, it will not be possible for me to use the filename of the tmpfile in a command line that should be ran by the OS, as in:

f = io.popen("python myprog.py " .. mytmpfile)

So my questions are:

Upvotes: 0

Views: 716

Answers (1)

shingo
shingo

Reputation: 27086

You can get a temp filename with os.tmpname.

local n = os.tmpname()
local f = io.open(n, 'w+b')
f:write(....)
f:close()
os.remove(n)

If your purpose is sending some data to a python script, you can also use 'w' mode in popen.

--lua
local f = io.popen(prog, 'w')
f:write(....)
#python
import sys
data = sys.stdin.readline()

Upvotes: 2

Related Questions