3

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'

Cœur
  • 37,241
  • 25
  • 195
  • 267
jwillis0720
  • 4,329
  • 8
  • 41
  • 74

1 Answers1

4

%%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
Matt
  • 27,170
  • 6
  • 80
  • 74