我可以制作一个简单的REPL来解析输入并根据自定义逻辑对其进行处理。我想知道是否以及如何在.py文件中创建REPL,就像在终端中打开python一样,但是包括对文件属性,方法和类的访问。例如,他们可以键入print('hello world')并执行此操作,或者可以在下面调用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")
答案 0 :(得分:2)
是的,无论您在python程序中的任何位置,都可以生成REPL。
import code
# launch a REPL
code.interact(local=globals())