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
|
#!/usr/bin/env python
# envstore - save and restore environment variables
#
# Copyright (C) 2008 Maximilian Gass <mxey@cloudconnected.org>
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Minor modifications by Daniel Friesel <derf@derf.homelinux.org>
import cPickle as pickle
import getopt
import os
import sys
def usage():
print >> sys.stderr, """envstore - save and restore environment variables
Usage:
envstore COMMAND [ARG]
Commands:
show List saved variables in human-readable format
eval Generate shell code to set the variables
save Save a variable
rm Delete a variable
clear Clear out the stored variable"""
sys.exit(1)
def save_store():
store_file = open(store_filename, 'w')
pickle.dump(store, store_file, protocol=-1)
store_file.close()
raw_file = open(raw_filename, 'w')
for item, value in store.iteritems():
print >> raw_file, "export " + item + "=" + value
raw_file.close()
def get_key():
try:
return sys.argv[2]
except IndexError:
print >> sys.stderr, "Usage: envstore " + command + " VARIABLE"
sys.exit(2)
try:
command = sys.argv[1]
except IndexError:
usage()
store_filename = "/tmp/envstore-" + str(os.getuid())
raw_filename = "/tmp/envstore-raw-" + str(os.getuid())
try:
store_file = open(store_filename)
store = pickle.load(store_file)
store_file.close()
except IOError:
store = {}
if command == "show":
for k, v in store.iteritems():
print k + "\t\t" + v
print "%i entries" % len(store)
elif command == "eval":
for k, v in store.iteritems():
print "export " + k + "=" + v
elif command == "save":
key = get_key()
try:
value = os.environ[key]
except KeyError:
print >> sys.stderr, key + " does not exist in environment"
sys.exit(3)
store[key] = value
save_store()
elif command == "rm":
key = get_key()
try:
del store[key]
except KeyError:
print >> sys.stderr, key + " does not exist in store"
sys.exit(4)
save_store()
elif command == "clear":
os.remove(store_filename)
os.remove(raw_filename)
else:
usage()
|