IPython Notebook Magic Functions with environment variables

1.4k views Asked by At

Can I use an environment variable with a magicfunction such as writefile in my ipthon notebook?

%env WORKING_DIR=/my/path/to/my/file
!echo $WORKING_DIR

/my/path/to/my/file

but

%%writefile $WORKING_DIR/myfile.txt
sometext

IOError: [Errno 2] No such file or directory: '$WORKING_DIR/myfile.txt'

1

There are 1 answers

2
Matt On BEST ANSWER

%%writefile $WORKING_DIR/myfile.txt does expansion of Python variable. so you need to have a WORKING_DIR python variable for this to work. $FOO works as env variable only if you are using a magics that shells out, and that get a raw $WORKING_DIR string. In which case the shell does the variable expansion.

It is possible but convoluted to do what you want, se example below:

In [1]: foo = 'a.py'

In [2]: %%writefile $foo
   ...: hi
   ...:
Writing a.py

In [3]: %env BAR=b.py
env: BAR=b.py

In [4]: import os

In [5]: %%writefile {os.environ['BAR']}
   ...: this is bar
   ...:
Writing b.py