将 Python 脚本的返回值存储在 bash 脚本中

2022-01-19 00:00:00 python return bash return-value

问题描述

我想从 bash 脚本执行 python 脚本,并且我想将 python 脚本的输出存储在一个变量中.

I want to execute a python script from a bash script, and I want to store the output of the python script in a variable.

在我的 python 脚本中,我将一些内容打印到屏幕上,最后我返回一个字符串:

In my python script, I print some stuff to screen and at the end I return a string with:

sys.exit(myString) 

在我的 bash 脚本中,我执行了以下操作:

In my bash script, I did the following:

outputString=`python myPythonScript arg1 arg2 arg3 `

但是当我使用 echo $outputString 检查 outputString 的值时,我得到了 Python 脚本打印到屏幕上的所有内容,但 不是 返回值myString

But then when I check the value of outputString with echo $outputString I get everything that the Python script had printed to screen, but not the return value myString!

我应该怎么做?

我需要该字符串,因为它告诉我 Python 脚本创建的文件所在的位置.我想做类似的事情:

I need the string because that tells me where a file created by the Python script is located. I want to do something like:

fileLocation=`python myPythonScript1 arg1 arg2 arg1`
python myPythonScript2 $fileLocation


解决方案

sys.exit(myString) 并不意味着返回这个字符串".如果您将字符串传递给 sys.exit, sys.exit 会将该字符串视为错误消息,并将该字符串写入 stderr.与整个程序的返回值最接近的概念是它的退出状态,它必须是一个整数.

sys.exit(myString) doesn't mean "return this string". If you pass a string to sys.exit, sys.exit will consider that string to be an error message, and it will write that string to stderr. The closest concept to a return value for an entire program is its exit status, which must be an integer.

如果您想捕获写入 stderr 的输出,您可以执行类似的操作

If you want to capture output written to stderr, you can do something like

python yourscript 2> return_file

你可以在你的 bash 脚本中做类似的事情

You could do something like that in your bash script

output=$((your command here) 2> &1)

但不能保证只捕获传递给 sys.exit 的值.写入 stderr 的任何其他内容也将被捕获,其中可能包括日志输出或堆栈跟踪.

This is not guaranteed to capture only the value passed to sys.exit, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.

示例:

test.py

print "something"
exit('ohoh') 

t.sh

va=$(python test.py 2>&1)                                                                                                                    
mkdir $va

bash t.sh

编辑

不知道为什么,但在这种情况下,我会编写一个主脚本和两个其他脚本...混合 python 和 bash 是没有意义的,除非你真的需要.

Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.

import script1
import script2

if __name__ == '__main__':
    filename = script1.run(sys.args)
    script2.run(filename)

相关文章