将用户输入插入后端 python shell

我正在做一个宠物项目,我正在尝试制作 Jupyter 的命令行版本(我完全理解这听起来有多愚蠢,“为什么不只使用 Python shell”,这只是为了好玩)。我一直在想办法在后台启动一个 Python 实例,允许我将用户的输入插入到那个 shell 中。但我就是找不到任何办法。有什么合理的方法可以做到这一点吗?

谢谢!

编辑:我正在考虑类似Jython的东西,但如果可能的话,我更愿意完全用 Python 来完成。


茅侃侃
浏览 97回答 1
1回答

MM们

我可以想到两种方法来做到这一点。第一种方法是exec用来执行用户输入的代码。while True:&nbsp; &nbsp; user_input = input("Python command to execute: ")&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; exec(user_input)&nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; print("Error thrown.")然而,这有其局限性。您必须编写一些自定义代码来捕获错误、适当地抛出错误等。第二种方法涉及更多,但也更通用。您使用everything is a file方法,并将用户输入(无论是通过 shell、网站还是其他任何方式)视为文件。然后,使用该文件执行它。您可以始终打开 shell,在执行之前检查文件是否已更新:import hashlibimport runpyimport timeFILE = "./file.py"def get_file_md5(file_name):&nbsp; &nbsp; with open(file_name, "rb") as f:&nbsp; &nbsp; &nbsp; &nbsp; return hashlib.md5(f.read()).hexdigest()md5 = get_file_md5(FILE)first_run = Truewhile True:&nbsp; &nbsp; current_md5 = get_file_md5(FILE)&nbsp; &nbsp; if md5 != current_md5 or first_run:&nbsp; &nbsp; &nbsp; &nbsp; first_run = False&nbsp; &nbsp; &nbsp; &nbsp; md5 = current_md5&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; runpy.run_path(FILE)&nbsp; &nbsp; &nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Error", e)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; time.sleep(1)您可能会发现我对另一个(模糊相关的)问题的回答很有趣并且很有用。关于下面。通知exec(object[, globals[, locals]])文件:在所有情况下,如果省略可选部分,代码将在当前范围内执行。如果仅提供全局变量,则它必须是一个字典(而不是字典的子类),它将同时用于全局变量和局部变量。所以你可以这样做:exec_globals = {}exec('a = 10; print(a)', exec_globals)print("\na in exec_globals: ", 'a' in exec_globals)print("exec_globals['a'] =", exec_globals['a'])print("\na in globals(): ", 'a' in globals())print(a)以上将输出:10a in exec_globals:&nbsp; Trueexec_globals['a'] = 10a in globals():&nbsp; FalseTraceback (most recent call last):&nbsp; File "test.py", line 7, in <module>&nbsp; &nbsp; print(a)NameError: name 'a' is not defined
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python