gpt4 book ai didi

python - 将命令通过管道传输到 Python REPL

转载 作者:行者123 更新时间:2023-11-28 19:43:53 24 4
gpt4 key购买 nike

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

例如,如果文件是

1 + 4
'a' + 'b'

那么输出应该是

>>> 1 + 4
5
>>> 'a' + 'b'
'ab'

有办法吗?

最佳答案

您可以使用 replwrap来自 pexpect为了实现这个目标,甚至有一个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),

哪个返回:

python replgo.py 
>>> 1 + 4
5
>>> 'a' + 'b'
'ab'

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

关于python - 将命令通过管道传输到 Python REPL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25557651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com