Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Bash variables into a Python script

I am running a bash script (test.sh) and it loads in environment variables (from env.sh). That works fine, but I am trying to see python can just load in the variables already in the bash script.

Yes I know it would probably be easier to just pass in the specific variables I need as arguments, but I was curious if it was possible to get the bash variables.

test.sh

#!/bin/bash source env.sh  echo $test1  python pythontest.py 

env.sh

#!/bin/bash  test1="hello" 

pythontest.py

? print test1 (that is what I want) 
like image 714
Tall Paul Avatar asked Jul 02 '13 20:07

Tall Paul


People also ask

How do you pass a variable to a shell script in Python?

You'll need to share what you've tried so far, or what the current code you have is. Try to keep it to the relevant portions, and not the entire script. Pass the variables into python as command line arguments then use something like getopt to parse the command line arguments within your python script.

Can I use bash in Python?

Bash is an implementation of the shell concept and is often used during Python software development as part of a programmer's development environment. Bash is an implementation of the shells concept.


1 Answers

You need to export the variables in bash, or they will be local to bash:

export test1 

Then, in python

import os print os.environ["test1"] 
like image 64
AMADANON Inc. Avatar answered Sep 23 '22 16:09

AMADANON Inc.