简体   繁体   English

捕获在容器内运行的 python 脚本的返回码

[英]capture returncode of python script running within the container

I'm creating a make-release script where the full application is prepared for deployment on the machine where it is needed.我正在创建一个 make-release 脚本,其中准备好完整的应用程序以在需要它的机器上部署。 It should be able to be build on a standard linux build machine (with docker) The thing is that I struggle to find a way to make a single python script independed from the build machine.它应该能够在标准的 linux 构建机器上构建(使用 docker)问题是我很难找到一种方法来制作独立于构建机器的单个 python 脚本。

"""Return hash of the key, used for prometheus web-portal access configuration"""

import sys
try:
    import bcrypt
except ImportError as e:
    print(e)
    sys.exit(1)

args = sys.argv

if len(args) == 2:
    try:
        PASSWORD = str(args[1])
        hashed_password = bcrypt.hashpw(PASSWORD.encode("utf-8"), bcrypt.gensalt())
        print(hashed_password.decode())
        sys.exit(0)
    except (IndexError, SystemError, ValueError, RuntimeError, UnicodeError) as e:
        print(e)
        sys.exit(1)

else:
    print('not enough arguments given')
    sys.exit(1)

Depending on the return code the print is either a hash or an error code.根据返回代码,打印是 hash 或错误代码。 It is therefor important to have the return code to handle the script different.因此,让返回代码来处理不同的脚本很重要。

# get hashed key for prometheus
HASHED_SECRET=$(python3 src/generate_prometheus_passhash.py ${PROMETHEUS_WEB_PASS})
RETURN_CODE=$?

if [ ${RETURN_CODE} == 0 ]; then
  <Use hash>
else
  echo "error: ${HASHED_SECRET}"
  exit 1;
fi

Does anyone have a good solution for this?有没有人对此有很好的解决方案?

You could use the ||您可以使用|| logic to set a bad hash in HASH if the return code is not 0 , and check for the value of $HASH with a if statement:如果返回码不是0 ,则在HASH中设置错误的 hash 的逻辑,并使用if语句检查$HASH的值:

script.py

#!/usr/bin/env python3
import sys

args = sys.argv

if (len(args) < 2):
    exit(1)
else:
    print("ABCDEFG")
    exit(0)

test.sh

#!/bin/sh

echo "Trying something that will fail"
HASH=$(python3 script.py || echo "BAD-HASH")
echo "HASH: $HASH"

echo "Trying something that will work"
HASH=$(python3 script.py a b c || echo "BAD-HASH")
echo "HASH: $HASH"

Output Output

$ ./test.sh
Trying something that will fail
HASH: BAD-HASH
Trying something that will work
HASH: ABCDEFG

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

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