Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export a variable from bash and use it in Python

I am trying to write a script which is executing couple of things on a Linux server and I would like to use bash for most of the Linux specific commands and only use Python for the most complex stuff, but in order to do that I will need to export some variables from the bash script and use them in the python script and I didn't find a way how I can do that. So I have tried to create two very little scripts to test this functionality: 1.sh is a bash script

#!/bin/bash

test_var="Test Variable"
export test_var
echo "1.sh has been executed"
python 2.sh

2.sh is a Python script:

#!/usr/bin/env python3

print("The python script has been invoked successfully")
print(test_var)

As you can guess when I execute the first script the second fails with the error about unknown variable:

$ ./1.sh
1.sh has been executed
The python script has been invoked successfully
Traceback (most recent call last):
  File "2.sh", line 4, in <module>
    print(test_var)
NameError: name 'test_var' is not defined

The reason why I am trying to do that is because I am more comfortable with bash and I want to use $1, $2 variables in bash. Is this also possible in Python?

[EDIT] - I have just found out how I can use $1 and $2 it in Python. You need to use sys.argv[1] and sys.argv[2] and import the sys module import sys

like image 900
Georgi Stoyanov Avatar asked May 29 '18 08:05

Georgi Stoyanov


2 Answers

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?

like image 129
Rishikesh Teke Avatar answered Nov 09 '22 23:11

Rishikesh Teke


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')
like image 30
Or Duan Avatar answered Nov 10 '22 00:11

Or Duan