쉘 스크립트 환경변수에 설정값을 지정하여 사용하는 방법은 설정값이 여러개이고 프로젝트가 한개 이상일때 관리하기가 번거로워지므로 프로젝트 디렉터리 .env 파일에 설정값을 저장하고 프로그램 시작시 .env 파일을 환경 변수에 저장하여 사용한다.
.env 파일에 일반적으로 패스워드와 다른 민감한 계정 정보를 포함하고 있기 때문에 Git 저장소에는 절대 추가해서는 안된다.
.girignore
.env
import_env.py
import os
"""
최상위 디렉터리에 있는 .env 파일을 읽어서 환견 변수에 설정한다.
.env 파일 패스워드와 다른 민감한 계정 정보를 포함하고 있기 때문에 Git 저장소에는 절대 추가해서는 안된다.
"""
def import_env(filename='.env'):
if os.path.exists('.env'):
print('Importing environment form .env...')
with open('.env') as file:
for no, line in enumerate(file, start=1):
# 앞뒤의 공백 제거
line = line.strip()
print('[{:2}]{}[end]'.format(no, line))
# 주석 무시
if len(line) > 0 and line[0] == '#':
print(' 주석 무시')
continue
pos = line.find('=')
if pos > 0:
name = line[0:pos].strip()
value = line[pos+1:].strip()
# '...' 또는 "..." 이면 앞뒤의 ' 또는 "을 제거
if len(value) >= 2 and value[0] == "'" and value[-1] == "'":
value = value[1:-1]
if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
value = value[1:-1]
os.environ[name] = value
# print('|' + name + '|=|' + value + '|')
print(' ' + name + '=' + value + '[end]')
import_env()
print(os.environ.get('host'))
print(os.environ.get('dbname'))
print(os.environ.get('user'))
print(os.environ.get('password'))
print(os.environ.get('port'))
print(os.environ.get('trace'))
print(os.environ.get('int'))
print(os.environ.get('str1'))
print(os.environ.get('str2'))
print(os.environ.get('str3'))