1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
#
# This file is part of Checkbox.
#
# Copyright 2008 Canonical Ltd.
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox. If not, see <http://www.gnu.org/licenses/>.
#
import os
import posixpath
from os import environ
from stat import ST_MODE, S_IEXEC
def get_variables():
return dict(environ)
def get_variable(name, default=None):
"""Get the value of an environment variable name.
Keyword arguments:
name -- name of the environment variable
"""
return environ.get(name, default)
def add_variable(name, value):
"""Add or change the value of an environment variable name.
Keyword arguments:
name -- name of the environment variable
value -- value given to the environment variable
"""
if value is not None:
environ[name] = value
def remove_variable(name):
"""Remove an environment variable name.
Keyword arguments:
name -- name of the environment variable
"""
if name in environ:
del environ[name]
def get_paths():
paths = []
if "PATH" in environ:
paths = environ["PATH"].split(":")
return paths
def get_path(command):
for path in get_paths():
absolute = posixpath.join(path, command)
if posixpath.exists(absolute):
mode = os.stat(absolute)[ST_MODE]
if mode & S_IEXEC:
return absolute
return None
def append_path(path):
"""Prepend a path to the PATH environment variable if it doesn't
exist already.
Keyword arguments:
path -- path to add
"""
environ_path = get_paths()
if path not in environ_path:
environ_path.append(path)
environ["PATH"] = ":".join(environ_path)
def prepend_path(path):
"""Prepend a path to the PATH environment variable if it doesn't
exist already.
Keyword arguments:
path -- path to add
"""
environ_path = get_paths()
if path not in environ_path:
environ_path.insert(0, path)
environ["PATH"] = ":".join(environ_path)
def remove_path(path):
"""Remove a path from the PATH environment variable if it exists
already.
Keyword arguments:
path -- path to remove
"""
environ_path = get_paths()
if path in environ_path:
environ_path.remove(path)
environ["PATH"] = ":".join(environ_path)
|