How to access Python variables notebook from python script
Question:
How to access Python variables (for example a Pandas dataframe in a Jupyterlab notebook) from a python script ?
I need to access a Dataframe (while I’m working in a notebook) from a python script, locally.
I need to access it without having to type more lines of code in the notebook, I am looking to establish a connection to the notebook from a python script.
Thanks.
Answers:
There’s a few ways to do this and I’m not sure I know which one is most suitable based on your description thus far:
If you are running a notebook and have a dataframe in-memory in the current namespace of the running notebook, let’s say my_df
for example, you can call and run a Python script in the current namespace using %run -i my_script.py
to invoke the script with the i
flag for interactivity so that it is running in the current notebook namespace. (See here for more about the magic run command and the -i
flag.) In other words, inside the script invoked in that way, my_df
, originally assigned in the active notebook, would be accessible as my_df
.
If you are using JupyterLab you can attach a console to a kernel and query the namespace that way. Since the console is IPython actually, you can also use the %run -i my_script.py
to invoke the script you are developing and the current namespace will be accessible from there, too. See here in the documentation, although as I noted here the last time I checked some of the specifics were outdated.
How to access Python variables (for example a Pandas dataframe in a Jupyterlab notebook) from a python script ?
I need to access a Dataframe (while I’m working in a notebook) from a python script, locally.
I need to access it without having to type more lines of code in the notebook, I am looking to establish a connection to the notebook from a python script.
Thanks.
There’s a few ways to do this and I’m not sure I know which one is most suitable based on your description thus far:
If you are running a notebook and have a dataframe in-memory in the current namespace of the running notebook, let’s say my_df
for example, you can call and run a Python script in the current namespace using %run -i my_script.py
to invoke the script with the i
flag for interactivity so that it is running in the current notebook namespace. (See here for more about the magic run command and the -i
flag.) In other words, inside the script invoked in that way, my_df
, originally assigned in the active notebook, would be accessible as my_df
.
If you are using JupyterLab you can attach a console to a kernel and query the namespace that way. Since the console is IPython actually, you can also use the %run -i my_script.py
to invoke the script you are developing and the current namespace will be accessible from there, too. See here in the documentation, although as I noted here the last time I checked some of the specifics were outdated.