Can I use workspace variables in an iPython script?

93 views
Skip to first unread message

Ian

unread,
Sep 15, 2009, 5:21:38 PM9/15/09
to APAM Python Users
Say I open iPython and create a variable
In [4]: x = 4
Then in ipython I run a script that uses a variable named 'x'. I'll
get an error saying that x isn't defined
In [6]: run myscript.py
---------------------------------------------------------------------------
NameError Traceback (most recent call
last)

/home/langmore/sync/hybrid_transport/code/myscript.py in <module>()
----> 1
2
3 print x
4
5

NameError: name 'x' is not defined
WARNING: Failure executing file: <myscript.py>


Is there some way around this other than converting myscript to a
function and passing variables to it. I want this functionality since
then I could manipulate objects and re-run scripts that use them.

Anil Raj

unread,
Sep 15, 2009, 5:24:59 PM9/15/09
to apam-pyt...@googlegroups.com
Does it make sense to define the variable as global? Have you tried it?

Anil
Sent from my iPhone

Ian Langmore

unread,
Sep 15, 2009, 6:09:15 PM9/15/09
to apam-pyt...@googlegroups.com
x as defined is global, e.g.

In [29]: globals()['x']
Out[29]: 4

shows that the globals dictionary has the key 'x'. I'm thinking that I
could pass the globals dictionary, then extract x from that. This
requires myscript being a function, but at least I can pass all values
in one shot. To that end, I create myscript.py

~~~~~~~~ myscript.py ~~~~~~~~~~~
def main(ipython_globals):
globals().update(ipython_globals)
print x
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Then from iPython

In [13]: x = 123
In [14]: myscript.main(globals())
123

So it works.

-Ian

--
- Ian

Ian Langmore

unread,
Sep 15, 2009, 6:35:47 PM9/15/09
to apam-pyt...@googlegroups.com
Forget it... the way I did things in that last email is full of
problems. For example, if 'x' is used within a loop then it won't
work. Trying to update locals() doesn't work either. Besides, I really
didn't want to make the script a function in the first place.

-Ian

--
- Ian

Reply all
Reply to author
Forward
0 new messages