1

我想知道 Python 脚本是否可以在运行时启动 Python 解释器,从而使变量可以从解释器中访问。

让我自己解释一下。假设我有以下脚本:

x = 20
LaunchInterpreter() #Imaginary way to launch the Interpreter

现在,解释器启动了,我们可以使用变量了。

>>> x               #x defined value by the script
20
>>> x*x
400
4

2 回答 2

1

如果您正在寻找动态解释器,您可以使用pdb. 它只是一个调试器,但应该仅用于该目的,但可以按以下方式使用;

x = 20
import pdb
pdb.set_trace()

现在您将拥有一个解释器,您可以使用这些变量。

我不知道这是否适合您的情况,但这是我能想到的与提供的信息最接近的事情。

编辑1:

如skishore评论中所述,您也可以code.interact(local=locals())这样使用:

x = 20
import code
code.interact(local=locals())
于 2013-08-11T22:33:11.520 回答
0

Python的-i命令行选项强制在脚本完成后启动命令解释器:

python --help
usage: /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
< ... >
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x

所以给定一个文件 test.py 包含:

x = 7
y = "a banana"

您可以启动 python 并-i选择执行您想要执行的操作。

python -i test.py
>>> x
7
>>> y
'a banana'
>>>
于 2013-08-11T22:59:08.207 回答