How can I pass bash Variable to python script.
bash.sh
while read -r db
do
Printf "%s\n" ${db} "Found"
done < path/to/file.txt
file.txt
db1
db2
db3
python.py
print(${db}_tables.replicate.fix)
How can I pass bash Variable to python script.
bash.sh
while read -r db
do
Printf "%s\n" ${db} "Found"
done < path/to/file.txt
file.txt
db1
db2
db3
python.py
print(${db}_tables.replicate.fix)
You can simply pass the variable value as a command line argument:-
python.py "${db}"
In you python program, you can use the sys.argv to accept and use argument:-
import sys
if len(sys.argv) == 1:
print "Usage: python.py <argument>"
else:
# use sys.argv[1]
You could modify this method to suit your needs...
# get_variable_from_external_command.py
# # with subprocess
# import subprocess
# proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
# out, err = proc.communicate()
# print(out)
# # without subprocess
# This method works with any Python from Version 1.4.0 to the current 3.8.0.
import os
filelist = os.popen("ls -l")
text = filelist.read()
filelist.close()
print(text)
EDIT:
'Printf' in your code should read 'printf'...
root@host:~# export GREETINGS='Hello'
root@host:~# python
>>>
>>> import os
>>> os.environ['GREETINGS']
'Hello'
>>>