管道命令到 Python REPL

Chr*_*tin 3 python read-eval-print-loop

我有一个包含 Python 语句的文件,我希望以这样一种方式运行 Python,即如果在 REPL 中运行这些命令,它将打印到标准输出中将显示的内容。

例如,如果文件是

1 + 4
'a' + 'b'
Run Code Online (Sandbox Code Playgroud)

那么输出应该是

>>> 1 + 4
5
>>> 'a' + 'b'
'ab'
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Noe*_*lkd 5

你可以使用replwrapfrompexpect来实现这个目标,甚至还有一个python方法:

from pexpect import replwrap

with open("commands.txt", "r") as f:
    commands = [command.strip() for command in f.readlines()]

repl = replwrap.python()
for command in commands:
   print ">>>", command
   print repl.run_command(command),
Run Code Online (Sandbox Code Playgroud)

返回:

python replgo.py 
>>> 1 + 4
5
>>> 'a' + 'b'
'ab'
Run Code Online (Sandbox Code Playgroud)

您需要获取最新版本的 pexpect。