Michael K
Michael K

Reputation: 2288

Use bash_profile aliases in jupyter notebook

It looks like my Jupyter notebook picks up everything that I export in my .bash_profile, but nothing that I alias.

I think ! uses bin/sh, so it's understandable that the aliases from the bash profile don't port over, but the %%bash magic also does not pick up the aliases I've written.

Is there a way to make the aliases in my bash profile available through ! (ideally) or, at the least, using %%bash?

Upvotes: 4

Views: 3993

Answers (1)

David Marx
David Marx

Reputation: 8558

This seems to work (python3, modified from a hack I found in a jupyter issue)

import subprocess

lines = subprocess.check_output('source ~/.bash_profile; alias',shell=True).split(b'\n')
manager = get_ipython().alias_manager
for line in lines:
    line = line.decode("utf-8") 
    split_index = line.find('=')
    cmd = line[split_index+1:]
    alias = line[:split_index]
    cmd = cmd[1:-1]
    print ("ALIAS:{}\t\tCMD:{}".format(alias,cmd))

    manager.soft_define_alias(alias, cmd)

Here's another alternative, which is less a solution than a workaround: you can define aliases locally to the notebook using the %alias magic, and make those aliases available in the future using the %store magic. More alias trickiness here: https://github.com/ipython/ipython/wiki/Cookbook:-Storing-aliases

More on the %store magic here: http://ipython.readthedocs.io/en/stable/config/extensions/storemagic.html

The next step is hacking the %store magic to persist these aliases: https://github.com/ipython/ipython/blob/master/IPython/extensions/storemagic.py


For posterity, here are the results of some experiments I ran before finally finding a solution:

I sourced my .bash_profile in a %%bash cell. From within that cell, I was able to interrogate the values of variables I defined in my .bash_profile, and was able to list aliased commands by invoking alias. However, I was still not able to use aliased commands. Additionally, variables defined in my .bash_profile were only accessible inside the cell with the source call: trying to access them in subsequent %%bash cell didn't work, and the alias command also failed. More interesting still: if I sourced using !, I wasn't able to interrogate variables defined in my bash profile nor list my aliases with ! shell commands in the same cell.

Suffice it say, the %%bash magic is finicky.

Upvotes: 4

Related Questions