chanwcom
chanwcom

Reputation: 4680

How can I use bash environment variables in IPython?

In .bashrc, I usually set a lot of environment variables to store path names.

So, I can go to that specific directory as follows:

cd $PARTICULAR_DIR

Are there any was to do this in IPython? The above command doesn't work, so I tried the following:

cd os.environ['PARTICULAR_DIR']

But the above one also doesn't work.

Could you please enlighten me?

Upvotes: 2

Views: 2606

Answers (1)

Mike Müller
Mike Müller

Reputation: 85612

You can use shell commands in IPython. Just prefix with !:

In [1]: !ls $PARTICULAR_DIR

Unfortunately, !cd does not work because the command is run in a separate shell that is discarded immediately after execution.

You can set bookmarks in IPython:

%bookmark <name> <dir> 

set the name <name> as shortcut for <dir>.

This procedure would work.

  1. Display the path in the variable:

    In [2]: !echo $PARTICULAR_DIR
    /path/to/dir/
    
  2. Create a new bookmark with copy and paste:

    In [3]: %bookmark PARTICULAR_DIR /path/to/dir/
    
  3. Switch to your desired dir:

    In [4]: %cd -b PARTICULAR_DIR
    

Bookmarks will persist through IPython sessions.

Upvotes: 6

Related Questions