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
  • 1
    unix.stackexchange.com/a/74246/117549 might help -- export the variable then use os.environ; or use unix.stackexchange.com/questions/237443/… and pass it as an argument. – Jeff Schaller Dec 10 '19 at 18:20
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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.