Wiki source code of Creating and accessing environment variables
Show last authors
author | version | line-number | content |
---|---|---|---|
1 | Notebooks can be opened from a link in a collab or other web page. | ||
2 | |||
3 | Some notebooks may need to be passed parameters, e.g. to indicate the context they are run in. For this, you can use the URL query parameters to add environment variables to a Jupyter Notebook. | ||
4 | |||
5 | For example, here is a link to a notebook: | ||
6 | |||
7 | (% style="color:#2ecc71" %)https:~/~/lab.ebrains.eu/user-redirect/lab/tree/shared/example_path/notebook.ipynb | ||
8 | |||
9 | To add environment variables that are accessible within that notebook (in this case LAB_MY_VARIABLE) use this URL: | ||
10 | |||
11 | (% style="color:#27ae60" %)https:~/~/lab.ebrains.eu/user-redirect/lab/tree/shared/example_path/notebook.ipynb(% style="color:#e74c3c" %)**?LAB_MY_VARIABLE=Hello** | ||
12 | |||
13 | You can add as many variables as you want but the query string needs to be properly formatted. You can find more info about the query string format [[here>>https://en.wikipedia.org/wiki/Query_string]]. | ||
14 | |||
15 | //Note**:** For the query parameters to be accessible in the notebook they need to be prefixed with LAB_ e.g. LAB_MY_VARIABLE=4 // | ||
16 | |||
17 | You can then access the environment variable from the notebook as in this code snippet: | ||
18 | |||
19 | {{code}} | ||
20 | import os | ||
21 | os.environ.get('LAB_MY_VARIABLE') | ||
22 | {{/code}} | ||
23 | |||
24 |