从python捕获返回值

2024-09-29 21:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个shell脚本TestNode.sh。此脚本的内容如下:

port_up=$(python TestPorts.py)
python TestRPMs.py

现在,我想捕获这些脚本返回的值。在

TestPorts.py

^{pr2}$

但当我检查了现有的答案时,它们对我来说并不管用。print正在推送变量port_up中的值,但我希望print应该{}在控制台上,而变量{}应该从return语句中获取值。有没有办法做到这一点?在

注意:我不想使用sys.exit()。没有这个可能达到同样的效果吗?在


Tags: 答案py脚本内容returnportsh语句
2条回答

but I wanted that print should print on the console and the variable port_up should get the value from return statement.

然后不要捕获输出。相反,请执行以下操作:

python TestPorts.py
port_up=$? # return value of the last statement
python TestRPMs.py

你可以:

^{pr2}$

但是我也不太乐意将“output”打印到stderr。在

或者,您可以跳过在python脚本中打印“8080working”消息,并从shell脚本打印它。在

def CheckPorts():
    if PortWorking(8080):
        return "8080"

以及:

port_up=$(python TestPorts.py)
echo "$port_up working"
python TestRPMs.py

要从Python脚本返回退出代码,可以使用sys.exit()exit()也可以使用。在Bash(和类似的)shell中,上一个命令的退出代码可以在$?中找到。在

但是,linuxshell退出代码是8位无符号整数,即在0-255范围内,如this answer中所述。所以你的策略行不通。在

也许您可以将“8080working”打印到stderr或日志文件,然后将“8080”打印到stdout,这样就可以用$()来捕获它。在

相关问题 更多 >

    热门问题