How to set env variable in Jupyter notebook

前端 未结 8 672
时光取名叫无心
时光取名叫无心 2020-11-27 13:05

I\'ve a problem that Jupyter can\'t see env variable in bashrc file, is there a way to load these variables in jupyter or add custome variable to it?

相关标签:
8条回答
  • 2020-11-27 13:27

    A related (short-term) solution is to store your environment variables in a single file, with a predictable format, that can be sourced when starting a terminal and/or read into the notebook. For example, I have a file, .env, that has my environment variable definitions in the format VARIABLE_NAME=VARIABLE_VALUE (no blank lines or extra spaces). You can source this file in the .bashrc or .bash_profile files when beginning a new terminal session and you can read this into a notebook with something like,

    import os
    env_vars = !cat ../script/.env
    for var in env_vars:
        key, value = var.split('=')
        os.environ[key] = value
    

    I used a relative path to show that this .env file can live anywhere and be referenced relative to the directory containing the notebook file. This also has the advantage of not displaying the variable values within your code anywhere.

    0 讨论(0)
  • 2020-11-27 13:31

    If you are using systemd I just found out that you seem to have to add them to the systemd unit file. This on Ubuntu 16. Putting them into the .profile and .bashrc (even the /etc/profile) resulted in the ENV Vars not being available in the juypter notebooks.

    I had to edit:

    /lib/systemd/system/jupyer-notebook.service
    

    and put in the variable i wanted to read in the unit file like:

    Environment=MYOWN_VAR=theVar
    

    and only then could I read it from within juypter notebook.

    0 讨论(0)
提交回复
热议问题