๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Lang/๐Ÿ Python

๐Ÿ Python * Linux(Ubuntu) ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์ฝ”๋“œ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ

1. ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์ €์žฅํ•˜๊ธฐ

- Terminal ์ฐฝ์—์„œ export command๋ฅผ ์ด์šฉํ•˜์—ฌ ํ™˜๊ฒฝ๋ณ€์ˆ˜๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

$ export ๋ณ€์ˆ˜๋ช…=๊ฐ’

 

- ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์‚ญ์ œ๋Š” unset command๋ฅผ ์ด์šฉํ•ฉ๋‹ˆ๋‹ค.

$ unset ๋ณ€์ˆ˜๋ช…

2. Python์—์„œ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ

- os.environ๋‚˜ os.getenv ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ™˜๊ฒฝ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

environ์€ ํ•ด๋‹น ๋ณ€์ˆ˜๊ฐ€ ์—†์„ ๊ฒฝ์šฐ ERROR ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ธฐ ๋•Œ๋ฌธ์— getenv ๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœํ•ฉ๋‹ˆ๋‹ค.

getenv๋Š” ํ•ด๋‹น ๋ณ€์ˆ˜๊ฐ€ ์—†์„ ๊ฒฝ์šฐ NONE ์„ returnํ•ฉ๋‹ˆ๋‹ค.

import os
 
print('\ngetting_system_value.py {}\n'.format('-'*20))
 
# ==================================
#   fine special value
#       - os.environ['value_name'] return string
#       - return "Error" if don't have value
#       - you should write "try - catch"
# ==================================
s = os.environ['XDG_RUNTIME_DIR']
print('\t1. An environment value >> {}\n'.format(s))
 
# ==================================
#   fine special value
#       - os.getenv('value_name') return string
#       - return None if don't have value
# ==================================
s = os.getenv('user_id')
print('\t2. An environment value >> {}\n'.format(s))
 
# ==================================================
#   fine all value
#       - os.environ.keys() return <class 'collections.abc.KeysView'>
#       - If you want sort them, you have to cast list from class
# ==================================================
ls = list(os.environ.keys())
ls.sort()
 
print('\t3. All environment value')
for item in ls:
    print('\t\t{}={}'.format(item, os.environ[item]))