简体   繁体   English

如何将Python变量传递给Bash?

[英]How do I pass a Python Variable to Bash?

How would I pass a Python variable to the Bash shell? 我如何将Python变量传递给Bash shell? It should work like this: foo="./RetVar.py 42" 它应该像这样工作: foo="./RetVar.py 42"

Replace the double-quotes with `s 用`s替换双引号

I have tried printing and sys.exiting the result, but to no avail. 我试过打印和sys.exiting结果,但无济于事。 How would I accomplish my goal? 我将如何实现目标?

foo="$(scriptthatprintssomething)"

That's it. 而已。 print . print Or sys.stdout.write() . 或者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. 在bash中,`cmd \\和$(cmd)都将被命令的输出替换。 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? 如果您仍然遇到此问题,是否可以向我们展示再现它的Python代码的最小示例,以帮助我们为您提供帮助?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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