Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In IPython console (Spyder), can I access a variable from main() after running my program?

Tags:

python

ipython

I am running my code using an IPython Console. I have a main() function that is executed as follows:

if __name__ == "__main__":  
    main()

Then main() calls a bunch of other functions and I don't use any classes. My question is, can I print or manipulate my variables interactively in the console after running my program?

Like if I don't have main() or any other functions, for example I can declare in my code:

a=1

And then it is easy to access from the console:

In [20]: a

Out[20]: 1

Thank you in advance if you can help with this noob question.

like image 807
user158037 Avatar asked Nov 01 '22 13:11

user158037


1 Answers

Have main return locals().

def main():
    # ...
    return locals()

if __name__ == "__main__":
    locals().update(main())

See also Making function variables from imported module available in iPython interactive namespace and Dump function variables to workspace in python/ipython

like image 93
keflavich Avatar answered Nov 15 '22 04:11

keflavich