Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a python script access variables defined in an interactive session?

So, for instance, I'm in an ipython session, and I have a variable,

var = [3,5,6]

defined in the ipython session, that I want to do something with by running a script, e.g.:

# my_script
plot(var)

so I want typing

%run my_script.py 

from the interactive session to plot var, as if I had typed:

plot(var)

within the interactive session.

Is this possible? How?

like image 707
capybaralet Avatar asked Feb 19 '15 20:02

capybaralet


People also ask

How do I run a Python script in interactive mode?

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .

How do you pass variables in a Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.

What is Python interactive mode?

Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole.

How do you reference a variable in Python?

Reference Visualization There are two ways of creating references in Python. One way is by assigning an expression to a variable: var = expression , where var is the variable's name and expression is the value assigned to the variable.


1 Answers

Yes, from the run command documentation: if you use %run -i it will run the script in your existing interactive session's namespace instead of a clean one, so it will have access to defined variables.

If you want similar in the standard python shell, you can run it with execfile: execfile('my_script.py')

like image 74
tzaman Avatar answered Sep 20 '22 05:09

tzaman