Code Runtime Code Recipe(CN)#
示例代码的背景信息请参考 semantic-code-runtime-cn
Detect Current Runtime In Python#
之前我们介绍了我们需要能检测出当前所在的 Runtime, 然后根据这个 Runtime 执行不同的业务逻辑, 所以你的代码中需要有一个模块来专门做这件事.
aws_ops_alpha
有一个模块 runtime 已经实现了很多自动检测当前 runtime 的逻辑. 你只需要 import 之后使用即可. 然后你就可以使用以下 API 了:
Runtime.current_runtime
: 获得当前的 runtime 的名字Runtime.current_runtime_group
: 获得当前 runtime group 的名字Runtime.is_xyz
orRuntime.is_xyz_runtime_group
: 判断当前的 Runtime 是不是某一个指定类型.
[3]:
import aws_ops_alpha.api as aws_ops_alpha
runtime = aws_ops_alpha.runtime
Specific Runtime
[2]:
runtime.current_runtime
[2]:
'local'
[4]:
runtime.is_local
[4]:
True
[5]:
runtime.is_github_action
[5]:
False
[6]:
runtime.is_aws_lambda
[6]:
False
Runtime Group
[3]:
runtime.current_runtime_group
[3]:
'local'
[4]:
runtime.is_local_runtime_group
[4]:
True
[5]:
runtime.is_ci_runtime_group
[5]:
False
[6]:
runtime.is_app_runtime_group
[6]:
False
Customize Runtime Detection#
如果你的 runtime 检测逻辑和 aws_ops_alpha
默认的不同, 例如检测是否在 Jenkins 时默认是用 BUILD_TAG
和 EXECUTOR_NUMBER
两个环境变量, 而你的 Jenkins 集群配置中使用的是 JENKINS_HOME
环境变量, 那么你可以 subclass 这个类, 并 override def is_jenkins(self):
方法, 自己实现对应的逻辑, 并且实例化一个 runtime = Runtime()
对象即可. 下面给出了一个例子.
[2]:
import os
import aws_ops_alpha.api as aws_ops_alpha
class Runtime(aws_ops_alpha.Runtime):
@property
def is_jenkins(self) -> bool:
"""
Reference:
- https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
"""
return "JENKINS_HOME" in os.environ
runtime = Runtime()
os.environ["JENKINS_HOME"] = "true"
runtime.is_jenkins
[2]:
True