bash 将字符串从 Python 返回到 Shell 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42808997/
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
Return string from Python to Shell script
提问by Андрей Далевский
I have Python code like:
我有 Python 代码,如:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
在我必须在 shell 脚本中执行此脚本并在 shell 变量中返回字符串之后,例如:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
不幸的是它不起作用。由于代码中的大量打印和输入(),stderr、stdout 和 stdin 的方式也不起作用。那么我该如何解决我的问题呢?谢谢你的答案
回答by chepner
That isn't even valid Python code; you are using return
outside of a function. You don't wan't return
here, just a print
statement.
那甚至不是有效的 Python 代码;您在return
函数之外使用。你不想return
在这里,只是一个print
声明。
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
(注意其他一些变化:
- Write your error messages to standard error, to avoid them being captured as well.
- Use
raw_input
, notinput
, in Python 2.
- 将您的错误消息写入标准错误,以避免它们也被捕获。
- 在 Python 2 中使用
raw_input
,而不是input
。
)
)
Then your shell
然后你的壳
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason notto, always quote parameter expansions.
应该管用。除非您有充分的理由不这样做,否则请始终引用参数扩展。
回答by volcano
Just use printinstead of return- you bash snippet expects result on STDOUT.
只需使用打印而不是返回- 您的 bash 代码段期望在 STDOUT 上得到结果。