0

Some users in my lab are used to Matlab's workspace and begin with the ipython notebook. So, I tried to simulate a workspace using ipython widgets. Inside the ipython.py, there is a workspace class. I've tried to use it as workspace(get_ipython()) but the class don't have access to ipython variables from a script. If I define this class inside the notebook, it works but not from a script.

So I put a main, I execute the file with exec() and I display the workspace object :

path = '/home/download/'
file = 'ipython.py'
exec(open(path+file).read())
wksp

The executiong method works but it's really ugly. Does someone have an idea how to make it better?

ipython.py

Thomas K
  • 39,200
  • 7
  • 84
  • 86
Etienne Cmb
  • 131
  • 7

2 Answers2

0

You should use

execfile()

Dont use exec()

example:

execfile('/Home/Downloads/lel.py')

or for you:

path = '/home/download/'
file = 'ipython.py'
execfile(path+file)

and in your ipython.py, use

if not __name__ == '__main__':
    # Call you object

Greetings!!

Milor123
  • 537
  • 4
  • 20
  • Thx ! I've Python 3, I've read that execfile has been removed. I can make a py2to3 for execfile, but instead of having one function, i'll have two. I think that I've to adapt ipython.py, but I just don't know how ! – Etienne Cmb Mar 31 '16 at 17:20
  • Hi dude, @EtienneCmb read this post for python 3x http://stackoverflow.com/a/437857/4941927 may be help you, if you need help, write me please :D – Milor123 Mar 31 '16 at 17:24
0

I might be missing something because I don't understand why you want to run this as a script. I would just remove if __name__ == '__main__ and then import wksp from the module in the notebook.

from ipython import wksp
display(wksp)

As explained in the comments the current code is calling eval() on the names defined in the notebook, that does not work because those names are not defined in the scope in which eval() is called. But you can avoid eval():

names = namespace.who_ls()
values = [namespace.shell.user_ns[name] for name in names]
types = [type(v) for v in varlist]
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
  • The problem is that my workspace class don't have access to ipython notebook variables. If the class is defined inside the notebook, it works. That's the reason for running it as a script, because it find variables. But, as you said, the best practice would be to import it – Etienne Cmb Mar 31 '16 at 19:07
  • It's sure. I'm forced to use this ugly loading way certainly because my class is not well defined... – Etienne Cmb Mar 31 '16 at 20:18