Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set shell environment variable via python script

Tags:

python

bash

shell

I have some instrument which requires environment variable which I want to set automatically from python code. So I tried several ways to make it happen, but none of them were successful. Here are some examples:

  1. I insert following code in my python script

    import os
    os.system("export ENV_VAR=/some_path")
    
  2. I created bash script(env.sh) and run it from python:

    #!/bin/bash
    export ENV_VAR=some_path
    
    #call it from python
    os.system("source env.sh")
    
  3. I also tried os.putenv() and os.environ["ENV_VAR"] = "some_path"

Is it possible to set(export) environment variable using python, i.e without directly exporting it to shell?

like image 327
Sergey Asryan Avatar asked Aug 16 '16 19:08

Sergey Asryan


People also ask

How do I set environment variables in Python?

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.

How do I set an environment variable in shell?

You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.


1 Answers

A shell function may do this. You need to print your export statement and eval that.

set_shell_env() {
    output=$(python print_export_env.py $*)
    eval $output
}
like image 168
thinker3 Avatar answered Sep 20 '22 14:09

thinker3