![使用解释器在终端中编译python3代码](https://linux22.com/image/1087215/%E4%BD%BF%E7%94%A8%E8%A7%A3%E9%87%8A%E5%99%A8%E5%9C%A8%E7%BB%88%E7%AB%AF%E4%B8%AD%E7%BC%96%E8%AF%91python3%E4%BB%A3%E7%A0%81.png)
当我使用命令简单地编译我的代码时python3 name.py
,它就会运行,但随后整个过程就结束了,我无法对编译后的数据做任何事情。
我希望以某种方式将我的程序编译到解释器中,并能够在该解释器中试验数据。例如,我想使用timeit(function(argument))
在 name.py 程序中定义和设置的函数和参数。
答案1
您正在寻找的是-i
开关。根据手册页:
-i When a script is passed as first argument or the -c option is
used, enter interactive mode after executing the script or the
command. It does not read the $PYTHONSTARTUP file. This can be
useful to inspect global variables or a stack trace when a
script raises an exception.
因此,如果您的脚本名称是name.py
您需要执行的,则运行:
python3 -i name.py
答案2
@daltonfury42 的答案是其中一种方法,但请注意,它会先运行脚本,然后再进入解释器。另一种方法是在与脚本相同的目录中运行解释器并导入它。
$ cat spam.py
def main(*args):
print("Called main() with args: ", args)
if __name__ == "__main__":
main("foo")
$ python3 spam.py
Called main() with args: ('foo',)
$ python3
>>> import spam
>>> spam.main("bar")
Called main() with args: ('bar',)
>>>