简体   繁体   English

Python Shell和execfile范围

[英]Python shell and execfile scope

I'm working from inside an ipython shell and often need to reload the script files that contain my functions-under-construction. 我在ipython shell内工作,通常需要重新加载包含我正在构造的函数的脚本文件。

Inside my main.py I have: 在我的main.py中,我有:

def myreload(): execfile("main.py") execfile("otherfile.py") def myreload():execfile(“ main.py”)execfile(“ otherfile.py”)

Calling myreload() works fine if I have already ran in the same ipython session the execfile commands directly. 如果我已经在同一ipython会话中直接运行execfile命令,则调用myreload()会很好。

However, for some reason, if the session is fresh and I just called execfile("main.py"), then myreload() doesn't actually make the functions from inside otherfile.py available. 但是,由于某种原因,如果会话是新鲜的,而我只是调用了execfile(“ main.py”),则myreload()实际上不会使otherfile.py内部的功能可用。 It doesn't throw any error though. 它不会引发任何错误。

Any ideas? 有任何想法吗?

Functions create a new scope. 函数创建新的作用域。 execfile() runs the script in the current scope. execfile()在当前作用域中运行脚本。 What you are doing will not work. 您正在做什么将无法正常工作。

If you seek to learn the actual correct usage of ipython (ie in interactive mode), then you should use magic commands like: 如果您想学习ipython的实际正确用法(即在交互模式下),则应使用魔术命令,例如:

%run

and

%edit

Check help for those functions with %run? 使用%run?检查这些功能的帮助%run? . This provides explicit examples. 这提供了明确的示例。

See also http://ipython.org/ipython-doc/stable/interactive/tutorial.html 另请参见http://ipython.org/ipython-doc/stable/interactive/tutorial.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM