Interacting with a running interactive console program from a different process
expect
is for a different purpose. It runs commands on a captive program. You, by contrast, are asking for a way to send commands to a process already running in the background.
As a bare-bones minimal example of what you want, let's create a FIFO:
$ mkfifo in
A FIFO is a special file that one process can write to while a different process reads from it. Let's create a process to read from our FIFO file in
:
$ python <in &
[1] 3264
Now, let's send python
a command to run from the current shell:
$ echo "print 1+2" >in
$ 3
The output from python
is 3
and appears here on stdout. If we had redirected python's stdout, it could be sent elsewhere.
What expect
does
expect
allows you to automate interaction with a captive command. As an example of what expect
can do, create a file:
#!/usr/bin/expect --
spawn python
expect ">>>"
send "print 1+2\r"
expect ">>>"
Then, run this file with expect
:
$ expect myfile
spawn python
Python 2.7.3 (default, Mar 13 2014, 11:03:55)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 1+2
3
>>>
Related videos on Youtube
user3268289
Updated on September 18, 2022Comments
-
user3268289 over 1 year
I have a console program with an interactive shell, similar to say, the Python interactive shell. Is there an easy way to start this interactive program A and then use another program B to run A? I want to do something like this:
$ /usr/bin/A& $ #find PID of A somehow $ somecommand "PID of A" "input string to send to A" output string from A $
What kind of "somecommand" could do this? Is this what "expect" is supposed to facilitate? I read the
expect
man page but still have no idea what it does. -
user3268289 over 9 yearsThank you sir, that was exactly what I was wondering. It's too bad man pages can't be as well written as your comment!
-
phil294 almost 7 yearsthis was very helpful, however some interactive prompts would need a
tail -f in | python &
-like syntax -
John1024 almost 7 years@Blauhirn Interesting. Can you give me an example?
-
phil294 almost 7 years@John1024 yes: try your python example yourself. the
print
command can be executed only once, the python shell stops after that. but concerning my previous comment: you'd need that forwish
: whilewish <in &
does work, it only accepts the first interaction (echo, cat instance). I needed to writetail -f in |wish &
for it to handle multiple echos. -thanks -
John1024 almost 7 yearsYes, I see that. On the other hand,
tail -f in | python
is not working for me at all: the python process hangs without ever responding.