【发布时间】:2013-05-06 07:31:15
【问题描述】:
我正在尝试构建一个应用程序,使用户能够与命令行交互式 shell(如 IRB 或 Python)进行交互。这意味着我需要将用户输入通过管道传输到 shell,然后将 shell 的输出返回给用户。
我希望这会像管道 STDIN、STDOUT 和 STDERR 一样简单,但大多数 shell 似乎对 STDIN 输入的响应与直接键盘输入不同。
例如,当我将 STDIN 输入python 时会发生以下情况:
$ python 1> py.out 2> py.err <<EOI
> print 'hello'
> hello
> print 'goodbye'
> EOI
$ cat py.out
hello
$ cat py.err
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'hello' is not defined
似乎 Python 将 STDIN 解释为脚本文件,并且它不通过管道传递任何交互界面,例如行首的“>>>”。它在第一行也失败并出现错误,因为我们在输出文件中看不到“再见”。
irb(交互式 Ruby)会发生以下情况:
$ irb 1> irb.out 2> irb.err <<EOI
> puts 'hello'
> hello
> puts 'goodbye'
> EOI
$ cat irb.out
Switch to inspect mode.
puts 'hello'
hello
nil
hello
NameError: undefined local variable or method `hello' for main:Object
from (irb):2
from /path/to/irb:16:in `<main>'
puts 'goodbye'
goodbye
nil
$ cat irb.err
IRB 的响应与 Python 不同:即,即使出现错误,它也会继续执行命令。但是,它仍然缺少 shell 接口。
应用程序如何与交互式 shell 环境交互?
【问题讨论】:
标签: shell stdout stdin interactive irb