Communicating with a console program.

Posted by Poromenos on Sat 27 Nov 2004 12:41 PM — 6 posts, 21,184 views.

Greece #0
Does anyone know of a way in any of the scripting languages for a program to read/write to a console program?
USA #1
Hmm. Not really. However, most of the ones able to use extended libraries and API calls may be usable to do that. Try googling on how to allow a windows application talk to a console application in a similar fashion. There are bound to be limits though, since you could feed 'known' commands to one, but not respond to prompts or other things that might appear, but are not part of a known set of events. For instance, a console application might let you hit a key to open a file, enter a name, then hit another key to play it once loaded. If the program could not find the file, then a dialog would pop up that you where not expecting and can not either identify or respond to. Unless the console application has a COM interface, talking to it is generally a one way street and you can't see the potholes before hand.

Now, if you really wanted to go nuts, you might capture a link to the console window itself, then manually read the entire screen, to look for prompts or the like at certain steps. However, I am pretty sure their is no direct way to either talk to them or find out what they are doing, unless they are specifically designed to allow it.
Greece #2
Hm, when I say console program I mean like the "dir" command, it just returns lines of text. I found something to do it in python, but I am still dissecting it. I was wondering if anyone knew of a way.
Australia Forum Administrator #3
What do you want to do exactly?

I tried this in Lua:

/os.execute "dir"

I saw a directory listing whizz by, and then disappear.

However by redirecting output, you can capture it, eg.


-- get a temporary file name
n = os.tmpname ()

-- execute a command
os.execute ("dir > " .. n)

-- display output
for line in io.lines (n) do
  print (line)
end

-- remove temporary file
os.remove (n)


Now to feed stuff into a console program, I imagine that writing to a file, and sending that *to* the program (ie. using "<") would do the trick.
Australia Forum Administrator #4
For this example to work you need to enable "io" and "os" in the sandbox that is set up for Lua under Global Preferences.
Greece #5
I'm afraid that what I want is very hard to do. I want to have MC play chess by linking Crafty (a chess engine) to it. Crafty has a prompt in which you enter your move, and it outputs the move it makes. I want to enter moves and capture its output. Unfortunately, it doesn't quit between moves (obviously, since the current game would be erased), and it takes quite a bit of time for it to output its move. I might be able to make something with Python and polling, now that I think of it. I'll get back to you.