5

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 Answer 1

6

%%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
Sign up to request clarification or add additional context in comments.

2 Comments

That's what I thought, but couldn't figure out the "{}" wrap. Thank you
{smth} and $smth are the same except $smth only work on smth in [a-zA-Z0-9_] IIRC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.