I’m having a problem with the Lua os.execute() command.
I just want to echo a word and write it into a file, like echo 'aword' > C:\folder\tempworkspace\foo to try the os.execute() command. The direcory C:\folder\tempworkspace exists, “foo” is the name of the file I want the command to create and fill with “aword”.
Later, when this works, I’d like to call R, using R -q -e "rbinom(1000,1,0.7)" > C:\folder\tempworkspace\foo.
I’ve already tried all the advice provided in
Lua programming – os.execute() is not working in Windows and Why won't applications in Program Files run using os.execute in lua?
but my problem seems to be a different one, maybe not even in the syntax, but somewhere else?
When I type those command directly in the Command Prompt, they work. I use Windows 7 Professional as an administrator, and Lua 5.1.4 with Eclipse.
Here is what I have tried so far:
os.execute("echo 'hehe' > C:\folder\tempworkspace\foo")
os.execute [["echo 'hehe' > C:\folder\tempworkspace\foo"]]
os.execute [["echo 'hehe' > 'C:\folder\tempworkspace\foo'"]]
os.execute [[echo 'hehe' > C:\folder\tempworkspace\foo]]
os.execute [[echo 'hehe' > C:\\folder\\tempworkspace\\foo]]
os.execute[[cmd.exe /c echo 'hehe' > C:\folder\tempworkspace\foo]]
os.execute("cmd.exe /c echo 'hehe' > C:\\folder\\tempworkspace\\foo")
os.execute("cmd.exe /c echo 'hehe' > 'C:\\folder\\tempworkspace\\foo'")
I’d be very grateful for any suggestions to improve my code. (Note: I’m writing to a file, because I want to use the output later in lua. Another way of doing this, using io.popen() has been suggested somewhere, but it is said to be platform dependent, anyway my Lua crashes when I try to use x = io.popen("R -q -e 'rnorm(10)'")).
Edit, after first answer:
Your sendMsg function somehow also does not work on my computer, and I don’t get any error, I really wonder what’s the problem. For pcall, am I doing this right? As the line print(err) does not print anything I wonder if I am doing correctly.
function sendMsg(cmd, msg, fpath)
local output = cmd.. " ".. msg.. " > ".. fpath
print(output)
os.execute(output)
end
function sendMsgArgs()
sendMsg("echo", "huhu", "C:\\merret\\tempworkspace\\foo");
end
err = pcall(sendMsgArgs)
if err == true then
print("THIS WORKED")
else
print("THIS DID NOT WORK")
print(err)
end
Edit: This was actually a Eclipse/editor issue. So I wanted to add some tags, such as lua-eclipse, but I can’t.
this snippet of code works on my Win7 box:
you need to make sure the file exists before you attempt to write to it. are you running this from the lua interpreter? do you get any error messages back when it fails to do the write?
alternatively – you can just use io.open() and write that way. wrapping this in a function and calling it using pcall() may give you more information if you have some sort of windows issue opening/reading to that location.
an example using pcall: