0

How do I assign a runtime variable value to an environment variable in python? Below is the code, I need to assign dynamic value of variable "exce" to environment variable "result"

Here is my snippet for the part :

try:
    logging.info("Process successfull")
except Exception as exce:  # pylint: disable=broad-except
        logging.error("Process Failed")
        logging.error(exce)
        with open(os.path.expanduser("~/.bashrc"), "a") as outfile:
            result = "export MYVAR=exce"
            outfile.write(result)
  • Does this answer your question? [How to set environment variables in Python?](https://stackoverflow.com/questions/5971312/how-to-set-environment-variables-in-python) – joshmeranda Jun 16 '22 at 16:00
  • No, Actually exce is a variable and it will store some value in it. So when I am assigning "export MYVAR=exce" to result- Inside bashrc file, MY VAR = exce, instead of the value. – Oshin aggrawal Jun 16 '22 at 16:06
  • just cast it to a string `os.environ["MYVAR"] = str(exce)` – joshmeranda Jun 16 '22 at 16:07
  • @joshmeranda Thanks for replying. But I am calling this environment variable from other file, so it's returning None. – Oshin aggrawal Jun 16 '22 at 16:21
  • Oh sorry I misunderstood. Environment variables are only capable of storing string values, and each process has its own set of environment variables, which are only passed on to child processes. If you are trying to pass any other type from script to script you will need to serialize (json, pickle, etc) that value, store it in some way, and read that value from the other script. Some common ways of doing this is via file, socket, or pipe. – joshmeranda Jun 16 '22 at 16:41
  • @joshmeranda Hey thanks for this explanation. May you please show some example for the same? Like in form of pipe or socket or file ? – Oshin aggrawal Jun 16 '22 at 16:54
  • If you want to store the value of exce into a file, you should change result = "export MYVAR=exce" to result = "export MYVAR=%s"%str(exce) – Teng Long Jun 21 '22 at 08:59

0 Answers0