[英]Simulate Python interactive mode
我正在為VK編寫一個私有的在線 Python 解釋器,它將密切模擬 IDLE 控制台。 只有我和白名單中的一些人才能使用此功能,沒有會損害我的服務器的不安全代碼。 但我有一個小問題。 例如,我發送帶有代碼def foo():
的字符串,我不想得到SyntaxError
但繼續逐行定義函數而不使用\\n
編寫長字符串。 exec()
和eval()
在這種情況下不適合我。 我應該用什么來達到預期的效果? 對不起,如果重復,仍然不要從類似的問題中得到它。
它歸結為讀取輸入,然后
exec <code> in globals,locals
在無限循環中。
參見例如IPython.frontend.terminal.console.interactiveshell.TerminalInteractiveSh ell.mainloop()
。
通過嘗試ast.parse()
在inputsplitter.push_accepts_more()
完成連續檢測。
實際上,IPython 已經有一個名為Jupyter Notebook的交互式 Web 控制台,因此最好的辦法是重用它。
Python 標准庫提供了code
和codeop
模塊來幫助您解決這個問題。 code
模塊直接模擬了標准的交互式解釋器:
import code
code.interact()
它還提供了一些工具,用於對其工作方式進行更詳細的控制和自定義。
如果你想從更基本的組件構建東西, codeop
模塊提供了一個命令編譯器,它可以記住__future__
語句並識別不完整的命令:
import codeop
compiler = codeop.CommandCompiler()
try:
codeobject = compiler(some_source_string)
# codeobject is an exec-utable code object if some_source_string was a
# complete command, or None if the command is incomplete.
except (SyntaxError, OverflowError, ValueError):
# If some_source_string is invalid, we end up here.
# OverflowError and ValueError can occur in some cases involving invalid literals.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.