0

I have a Python script that I want to pass a bash variable to.

bash.sh

while read -r db
do
Printf  "%s\n" ${db} "Found"
done < path/to/file.txt

output: db1 db2 db3

file.txt

db1
db2
db3

python.py

print(${db},+"_tables.replicate.fix")

I need an output of : db1 db2 db3

How can the python file know what the db variable holds in the bash file?

  • I see no connection here between Bash script and Python script. Guessing that it would be called after the printf line in Bash? – pbm Dec 10 '19 at 17:16
  • are you asking how to write to a file in Bash then read from that same file in Python? – CyberStems Dec 10 '19 at 17:28
  • OP is possibly asking how to do this within a bash heredoc. or, maybe how to use the export option to export the variable and then source later from a script. – Rakib Fiha Dec 10 '19 at 17:39
  • 2
    ... or perhaps they are asking how to use sys.argv? – steeldriver Dec 10 '19 at 17:50
  • @Kwesi Gene, unclear what you are asking; Please, provide more details – Gilles Quénot Dec 10 '19 at 17:52
  • The $db variable in the .sh file returns db1, db2,db3. I want to use the same variable "$db" in the python file to return the same output. Not sure how to make the two scripts talk together – Kwesi Gene Dec 10 '19 at 17:57
  • 1
    https://unix.stackexchange.com/a/74246/117549 might help -- export the variable then use os.environ; or use https://unix.stackexchange.com/questions/237443/is-it-possible-to-pass-arguments-into-a-python-script?rq=1 and pass it as an argument. – Jeff Schaller Dec 10 '19 at 18:20

1 Answers1

1

The easiest way to "export" the shell db variable to a program that the script runs would be to pass it as an argument, and then the python command can read it from sys.argv.

It might look like this:

while IFS= read -r db
do
printf  "%s\n" "${db} Found"
python -c 'import sys; print("db: %s" % sys.argv[1])' "$db"
done < path/to/file.txt
Guss
  • 12,628