python校验环境变量是否设置

调研:

https://docs.python.org/2.7/library/os.html?highlight=os%20sys#os.environ

A mapping object representing the string environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C.

官方解释:python2.7中os.environ表示一个字符串所对应环境的映像对象。举例:os.environ['HOME']表示你的主目录。

方法1:具体实现方式如下,主要是了解 os.environ的使用
# -*- coding: utf-8 -*-
import os
import sys
import json
import logging

requiredEnv = ['USER', 'HOME', 'PATH', 'LC_COLLATE', 'LAN', 'shell']  # 设置必要检查的环境变量


def env_check():
    """ This script will check to see if all of the environment variables required are set. """
    lack_env = []
    env = os.environ
    for per_req_env in requiredEnv:
        if per_req_env not in env:
            lack_env.append(per_req_env)
    return lack_env


def main():
    """ main func """
    lack_env = env_check()
    if not lack_env:
        print "all of the environmentvariables required are set"
    else:
        print "%s environment variables required are lack set" % lack_env


if __name__ == '__main__':
    main()
方法2,参见github,学习后更新

https://github.com/geekcomputers/Python/blob/master/env_check.py>
分析: 方法1是用全局变量requiredEnv维护需要检查的环境变量。方法2是维护一个conf文件

你可能感兴趣的:(python校验环境变量是否设置)