Shell 调用 py 脚本,接收返回值

1.py 脚本的 sys.exit([arg])

直接调用exit(),注意是个函数要加括号,无参数默认返回码0,表示脚本运行成功。
参数可以是整数也可以是其他对象,若是其他对象则返回码为1,如错误信息字符串,同时字符串内容也会输出。

# test.py
print 'test'
exit('error message')

# 运行脚本
python test.py
echo $?    # 上个命令的退出状态,或函数的返回值。一般情况下,大部分命令执行成功会返回 0,失败返回 1。

输出
test
error message
1

2.获取 py 脚本中 print 内容,同样通过 output=python .py 或 output=$(python .py) 获取,通过这种方式 py 中的 print 不会在控制台输出。

# test.py
print 'test'
exit('error message')

# 运行脚本
x=`python test.py`
echo $?
echo ${x}

输出  
error message
1   
test
posted @ 2022-08-19 17:44  Oops!#  阅读(475)  评论(0编辑  收藏  举报