Export a variable from bash and use it in Python

Check python extension it should be .py instead of .sh 1.sh

#!/bin/bash
 test_var="Test Variable"
 export test_var
 echo "1.sh has been executed"
 python 2.py

os library will gave you the access the environment variable. Following python code will gave you the required result,

#!/usr/bin/env python3
import os
print("The python script has been invoked successfully")
print(os.environ['test_var'])

Check for reference : How do I access environment variables from Python?


To use environment variables from your python script you need to call:

import os
os.environ['test_var']

os.environ is a dictionary with all the environment variables, you can use all the method a dict has. For instance, you could write :

os.environ.get('test_var', 'default_value')