如何将 Python 变量传递给 Bash?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2796932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:04:57  来源:igfitidea点击:

How do I pass a Python Variable to Bash?

pythonlinuxbashunix

提问by user336537

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

我如何将 Python 变量传递给 Bash shell?它应该像这样工作: foo="./RetVar.py 42"

Replace the double-quotes with `s

用 `s 替换双引号

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

我试过打印和 sys.exiting 结果,但无济于事。我将如何实现我的目标?

回答by Ignacio Vazquez-Abrams

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.

就是这样。print. 或者sys.stdout.write()。或者之类的。如果脚本不可执行,那么您需要明确指定解释器。

foo="$(python scriptthatprintssomething.py)"

回答by seamus

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

在 bash 中,``cmd\和 $(cmd) 都将被命令的输出替换。这允许您将程序的输出分配给变量,例如

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.

通常你用双引号把它括起来,这样你的输出中就可以有空格。它必须是双引号,因为单引号内的内容不会被执行。

回答by Alex Martelli

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?

所以大概你尝试打印的方式是不正确的。(这与使用旧式反引号或新式结构(例如$())完全无关)。如果您仍然遇到此问题,能否向我们展示重现该问题的 Python 代码的最小示例,以帮助我们帮助您?