简体   繁体   中英

How do I pass a Python Variable to Bash?

How would I pass a Python variable to the Bash shell? It should work like this: foo="./RetVar.py 42"

Replace the double-quotes with `s

I have tried printing and sys.exiting the result, but to no avail. How would I accomplish my goal?

foo="$(scriptthatprintssomething)"

That's it. print . Or sys.stdout.write() . Or the like. If the script isn't executable then you'll need to specify the interpreter explicitly.

foo="$(python scriptthatprintssomething.py)"

In bash both ``cmd \\ and $(cmd) will be replaced by the output of the command. This allows you to assign the output of a program to a variable like

foo=`some command`

or

foo=$(some command)

Normally you wrap this in double quotes so you can have spaces in your output. It must be double quotes as stuff inside single quotes will not be executed.

Your desired form works just fine:

$ cat >Retvar.py
#!/usr/bin/python
import sys
print sys.argv[1]
$ chmod +x RetVar.py 
$ foo=`./RetVar.py 42`
$ echo $foo
42
$ 

so presumably the ways in which you had tried printing were incorrect. (This is quite independent from using the older-style backquotes, or newer-style constructs such as $() ). If you still have this problem, can you show us the minimal example of Python code that reproduces it, to help us help you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM