有没有办法在.py文件中创建一个 REPL,让用户可以访问它的整个上下文?



我可以制作一个简单的REPL,解析输入并根据自定义逻辑进行处理。我想知道是否以及如何在.py文件中创建REPL,类似于在终端中打开python,但包括对文件的属性、方法和类的访问。例如,他们可以键入print("helloworld"(并执行该操作,也可以在下面调用cpu.ram_write((。

# Should be obvious what I am doing here. There's a CPU class above with a few methods and properties. 
cpu = CPU()
print(cpu.ram_read(4))
cpu.ram_write(5,4)
print(cpu.ram_read(4))
# This is where I want the REPL
while True:
x = input("Enter a command: ")
if x == 'q':
quit()
try:
x
except:
print("error")

是的,可以从python程序中的任何位置生成REPL。

import code
# launch a REPL
code.interact(local=globals()) 

参考文件

最新更新