控制Python交互式shell的输入/输出
我必须评估(数百万个)Python 表达式,例如 (int(a) >> 8 == 4) 和 b
在我的 OCaml 程序中。有 pycaml 但我没能让它工作。
于是我转向了另一个想法:直接控制Python解释器的输入/输出。
理想情况下,我想拦截解释器本身的输入/输出。 通过发送 a = 3
b = 5
a > b
到解释器,然后我就能够得到结果 False
,就好像我是通过键盘完成的一样。
>>> a = 3
>>> b = 5
>>> a > b
False
>>>
但是,我的代码无法按预期工作(而相同的代码适用于某些交互式程序)
let (readme, writeme) = Unix.open_process "python -u";;
let _ = output_string writeme "3 + 5\n" in
let _ = flush writeme in
let result = input_line readme in
print_endline result;;
我尝试将 3 + 5\n
更改为 print 3\n
,但它仍然挂在 input_line
处。 有没有更好的方法来做到这一点?我需要评估很多 表达式,所以我真的不想通过临时文件来做到这一点。任何帮助表示赞赏, 谢谢。
I have to evaluate (millions of) Python expressions e.g. (int(a) >> 8 == 4) and b
in my OCaml program. There is pycaml
but I failed to get it working.
So I turned to another idea: control the input/output of Python interpreter directly.
Ideally I would like to intercept both the input/output of the interpreter itself.
By sending a = 3
b = 5
a > b
to the interpreter, I would then be able to get the result False
, as if I have done this by keyboard..
>>> a = 3
>>> b = 5
>>> a > b
False
>>>
However, my code doesn't working as expected (while the same code worked for some interactive program)
let (readme, writeme) = Unix.open_process "python -u";;
let _ = output_string writeme "3 + 5\n" in
let _ = flush writeme in
let result = input_line readme in
print_endline result;;
I tried changing 3 + 5\n
to print 3\n
, but it still hangs at input_line
.
Is there any better way to do this? I would need to evaluate quite a lot of
expressions, so I don't really want to do this via a temp file. Any help appreciated,
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会评论整个概念的奇怪之处(驱动 python 评估来自 o'caml 的表达式),但似乎你可能想考虑编写一个 python 程序,它是一个读取/写入字符串的 eval 循环从/到管道。查找 eval 命令。
I'm not going to comment on the weirdness of the entire concept (driving python to evaluate expressions from o'caml) but it seems like you might want to look into writing a python program that is an eval cycle that reads/writes a string from/to a pipe. Look up the eval command.
您可以通过命令行向解释器提供命令:
这足以满足您的需求吗?
如果您担心重复打开解释器,您可以一次生成并计算许多表达式。我不确定上限是多少,但我能够评估并打印
a = 3; 的 200 个串联副本。 b = 5;打印一个> b;
没有任何问题。You can supply a command to the interpreter through the command line:
Is that adequate for your needs?
If you're concerned about opening the interpreter repeatedly, you could generate and evaluate many expressions at once. I'm not sure what the upper limit is, but I was able to evaluate and print 200 concatenated copies of
a = 3; b = 5; print a > b;
without any problem.