bpython -i &;命名空间
我似乎无法在任何地方找到这个答案。
举个简单的例子:
# myclass.py
class MyClass:
def __init__(self):
print 'test'
def main():
my_class_instance = MyClass()
if __name__ == '__main__':
main()
some_var = 'i exist! ... but I think I'm in global namespace?'
如果我运行 bpython -i myclass.py,我会执行程序 &进入 bpython 环境。无论我位于哪个命名空间 - my_class_instance 都不存在。然而, some_var 确实存在 - main 函数本身也存在。
无论如何,当我进入交互式提示时,我是否可以将该主函数中存在的任何对象拉入我所在的命名空间中?或者还有什么我应该做的吗?
I can't seem to find this answer anywhere.
Given the trivial example:
# myclass.py
class MyClass:
def __init__(self):
print 'test'
def main():
my_class_instance = MyClass()
if __name__ == '__main__':
main()
some_var = 'i exist! ... but I think I'm in global namespace?'
If I run bpython -i myclass.py, I execute the program & drop into the bpython environment. Whatever namespace I'm in - my_class_instance does not exist. However, some_var does exist - and so does the main function itself.
Is there anyway that I can pull any objects that exist in that main function into the namespace I'm in when I drop into that interactive prompt? Or is there something else I should do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
my_class_instance
位于main
的命名空间中,因此您在main
之外看不到它。使用全局代替:my_class_instance
is inmain
's namespace, so you can't see it outside ofmain
. Use a global instead:当我想从运行 main 函数中返回一些东西时,我有时会使用的另一个技巧是在 main 末尾返回我需要的东西。
因此,例如,如果我需要顶层主函数中的一个实例和一些其他变量,则可以这样做:
如果您现在使用 bpython -i scriptname 调用脚本,您将在全局命名空间中拥有变量“ret”和 ret [0] 包含您的类实例,ret[1] 包含数字 4。
Another trick I sometimes use when I want something back from running a main function is to return what I need at the end of main.
So, for example if I need an instance and some other variable from the main function in the top level one could do:
If you now call your script with bpython -i scriptname you will have the variable 'ret' in the global namespace and ret[0] has your class instance, ret[1] has the number 4.
在 python 2.7 上使用交互式 bpython,
__name__
等于__console__
。所以你的函数main()
可能永远不会被调用。一个 hack 是这样写:Using interactive bpython over python 2.7,
__name__
is equal to__console__
. So your functionmain()
may be never called. A hack would be to write: