Can I access python variables within a `%

前端 未结 5 791
青春惊慌失措
青春惊慌失措 2020-12-12 17:55

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

Perhaps as command line argume

5条回答
  •  执笔经年
    2020-12-12 18:30

    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:

    l = ['A', 'B', 'C']
    

    then if you give it directly to the magic option the next cell:

    %%bash -s "$l"
    for i in $1
    do
    echo $i
    done
    

    It will be oddly split like this:

    ['A',
    'B',
    'C']
    

    The simplest answer is to put code inside braces {} to transform your python list in bash list, like the following:

    %%bash -s "{" ".join(l)}"
    for i in $1
    do
    echo $i
    done
    

    Which give the expected output:

    A
    B
    C
    

提交回复
热议问题