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)?
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)?
To include python variables within bash commands run using the syntax
!<some command>
you can use{<variable>}
as follows:While this is slightly different from what the OP asked, it is closely related and useful in performing a scripting task. This post has more great tips and examples of using shell command within IPython and Jupyter notebooks.
One problem is, if the variable that you want to give to your bash is a list, it does not work as expected.
For example, in one python cell:
then if you give it directly to the magic option the next cell:
It will be oddly split like this:
The simplest answer is to put code inside braces
{}
to transform your python list in bash list, like the following:Which give the expected output:
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: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 ofstr(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 adatetime.datetime
withstr(myPythonVar)
as"2013-10-30 05:04:09.797507"
, the above bash script would receive 3 positional variables, the first two with values2013-10-30
and05:04:09.797507
. It's output would be:If you want to name the variables and you're running linux, here's an approach:
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.Just to note a variation, if you need to pass something other than a simple variable to the bash script:
goes gruesomely wrong, but
works nicely.
No,
%%script
magic are autogenerated and don't do any magic inter-process data communication. (which is not the case for%%R
but which is a separate magic in its own class with extra care fromR
peoples)But writing your own magic that does it is not too hard to do.