Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access python variables within a `%%bash` or `%%script` ipython notebook cell?

Is there a way to access variables in the current python kernel from within a %%bash or other %%script cell?

Perhaps as command line arguments or environment variable(s)?

like image 995
drevicko Avatar asked Oct 25 '13 01:10

drevicko


People also ask

What is a magic function in jupyter notebook?

What are the magic commands? Magic commands are special commands that can help you with running and analyzing data in your notebook. They add a special functionality that is not straight forward to achieve with python code or jupyter notebook interface. Magic commands are easy to spot within the code.

What is a cell magic in python?

Cell Magics They have %% character prefix. Unlike line magic functions, they can operate on multiple lines below their call. They can in fact make arbitrary modifications to the input they receive, which need not even be a valid Python code at all. They receive the whole block as a single string.

What is line magic function?

Magic commands come in two flavors: line magics, which are denoted by a single % prefix and operate on a single line of input, and cell magics, which are denoted by a double %% prefix and operate on multiple lines of input.


1 Answers

Python variables can be accessed in the first line of a %%bash or %%script cell, and so can be passed as command line parameters to the script. For example, with bash you can do this:

%%bash -s "$myPythonVar" "$myOtherVar" echo "This bash script knows about $1 and $2" 

The -s command line option allows you to pass positional parameters to bash, accessed through $n for the n-th positional parameter. Note that what's actually assigned to the bash positional variable is the result of str(myPythonVariable). If you're passing strings containing quote characters (or other bash-sensitive characters), you'll need to escape them with a backslash (eg: \").

The quotes are important - without them the python variables (string representations) are split on spaces, so if myPythonVar was a datetime.datetime with str(myPythonVar) as "2013-10-30 05:04:09.797507", the above bash script would receive 3 positional variables, the first two with values 2013-10-30 and 05:04:09.797507. It's output would be:

This bash script knows about 2013-10-30 and 05:04:09.797507 

If you want to name the variables and you're running linux, here's an approach:

%%script env my_bash_variable="$myPythonVariable" bash echo myPythonVariable\'s value is $my_bash_variable 

You can specify multiple variable assignments. Again beware of quotes and other such things (here bash will complain bitterly!). To grok why this works, see the env man page.

like image 188
drevicko Avatar answered Oct 06 '22 07:10

drevicko