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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
|
#!/usr/bin/env python
#
# Archey [version 0.3.0]
#
# Archey is a simple system information tool written in Python.
#
# Copyright 2010 Melik Manukyan <melik@archlinux.us>
#
# ASCII art by Brett Bohnenkamper <kittykatt@silverirc.com>
# Changes Jerome Launay <jerome@projet-libre.org>
# Fedora support by YeOK <yeok@henpen.org>
#
# Distributed under the terms of the GNU General Public License v3.
# See http://www.gnu.org/licenses/gpl.txt for the full license text.
# Import libraries
import os, sys, subprocess, optparse, re, linecache
from optparse import OptionParser
from getpass import getuser
from time import ctime, sleep
#---------------Output---------------#
output = [
'User',
'Hostname',
'Distro',
'Kernel',
'Uptime',
'WindowManager',
'DesktopEnvironment',
'Shell',
'Terminal',
'Packages',
'CPU',
'RAM',
'Disk'
]
#---------------Dictionaries---------------#
class NoDeleteDict(dict):
"""
This dict silently disables deletions. This is because allthough we will want users to be able to
edit these dicts from their config files, we don't want them to muck up somthing important, so we
disable deletions to protect them from themselves.
>>>dic = NoDeleteDict({'a':1, 'b':2})
We can still access items normally:
>>>dic['a']
1
But when we delete items, nothing happens:
>>>del dic['b']
>>>dic['b']
2
"""
def __delitem__(self, name):
return
COLOR_DICT = NoDeleteDict({
'Arch Linux': ['\x1b[0;34m', '\x1b[1;34m'],
'Ubuntu': ['\x1b[0;31m', '\x1b[1;31m', '\x1b[0;33m'],
'Debian': ['\x1b[0;31m', '\x1b[1;31m'],
'Mint': ['\x1b[0;32m', '\x1b[1;37m'],
'Crunchbang': ['\x1b[1;37m'],
'Fedora': ['\x1b[0;34m', '\x1b[1;37m'],
'Clear': '\x1b[0m'
})
DE_DICT = NoDeleteDict({
'gnome-session': 'GNOME',
'ksmserver': 'KDE',
'xfce4-session': 'Xfce',
'lxsession': 'LXDE'
})
WM_DICT = NoDeleteDict({
'awesome': 'Awesome',
'beryl': 'Beryl',
'blackbox': 'Blackbox',
'compiz': 'Compiz',
'dwm': 'DWM',
'enlightenment': 'Enlightenment',
'fluxbox': 'Fluxbox',
'fvwm': 'FVWM',
'i3': 'i3',
'icewm': 'IceWM',
'kwin': 'KWin',
'metacity': 'Metacity',
'musca': 'Musca',
'openbox': 'Openbox',
'pekwm': 'PekWM',
'ratpoison': 'ratpoison',
'scrotwm': 'ScrotWM',
'wmaker': 'Window Maker',
'wmfs': 'Wmfs',
'wmii': 'wmii',
'xfwm4': 'Xfwm',
'xmonad': 'xmonad'
})
LOGO_DICT = NoDeleteDict({'Arch Linux': '''{color[1]}
{color[1]} + {results[0]}
{color[1]} # {results[1]}
{color[1]} ### {results[2]}
{color[1]} ##### {results[3]}
{color[1]} ###### {results[4]}
{color[1]} ; #####; {results[5]}
{color[1]} +##.##### {results[6]}
{color[1]} +########## {results[7]}
{color[1]} ######{color[0]}#####{color[1]}##; {results[8]}
{color[1]} ###{color[0]}############{color[1]}+ {results[9]}
{color[1]} #{color[0]}###### ####### {results[10]}
{color[0]} .######; ;###;`\". {results[11]}
{color[0]} .#######; ;#####. {results[12]}
{color[0]} #########. .########` {results[13]}
{color[0]} ######' '###### {results[14]}
{color[0]} ;#### ####; {results[15]}
{color[0]} ##' '## {results[16]}
{color[0]} #' `# {results[17]}
\x1b[0m'''})
PROCESSES = str(subprocess.check_output(('ps', '-u', getuser(), '-o', 'comm',
'--no-headers')), encoding='utf8').rstrip('\n').split('\n')
#--------------Exceptions-------------#
class ArcheyException(Exception): pass
#---------------Classes---------------#
class Output(list):
results = []
def __init__(self):
self.distro = self.__detectDistro()
super().__init__()
def __detectDistro(self):
if os.path.exists('/etc/pacman.conf'):
return 'Arch Linux'
else:
sys.exit("Unsupported distro")
def _color(self, index):
"""
Returns the escape code for either:
a) The color scheme of the distro value stored in self.distro
or
b) The value of the entry in COLOR_DICT for the key passed
>>out = Output()
>>out._color(1) == COLOR_DICT[out.distro][1]
>>out._color(out.distro) == COLOR_DICT[out.distro]
"""
if isinstance(index, str):
return COLOR_DICT[index]
return COLOR_DICT[self.distro][index]
def _get_logo(self):
return LOGO_DICT[self.distro]
def _center_results(self, results, max_length=17):
"""
Centers a list of results. Length of desired list can be given via max_length kwarg.
>>>out = Output()
>>>out._center_results([1])
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 1, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
>>>out._center_results([1], max_length=3)
[' ', 1, ' ']
"""
length = len(results)
if length > max_length:
return results[:max_length + 1]
center = int(max_length/2)
start = int(center - length/2)
new_results = list(' ' * max_length)
new_results[start:start + length - 1] = results
return new_results
def _get_results(self):
"""
Returns a dict of the keys and values of the currently registered display classes.
NOTE: Will not include any key value pairs where either evaluates to False.
>>>out = Output()
>>>class TestDisplay():
... key = 'Foo'
... value = 'Bar'
... key_value_pair = lambda self: {self.key: self.value}
...
>>>out.append(TestDisplay())
>>>out._get_results()
{'Foo': 'Bar'}
"""
return {key:value for key, value in [disp.key_value_pair() for disp in self] if key and value}
def output(self):
"""
Outputs the archey logo and information. Reads Display classes from the internal list,
and formats them, adding color. The final pretty list is then centered (though other alignments
may be added) and printed.
"""
results = self._get_results()
unformatted_stn = '{color}{key}: {clear}{value}{clear}'
pretty_results = []
for key, value in results.items():
try:
formatted_stn = unformatted_stn.format(color=self._color(1), key=key, value=value,
clear=self._color('Clear'))
except:
#Fail silently, have a debug option later for noisy fail?
pass
else:
pretty_results.append(formatted_stn)
centered_results = self._center_results(pretty_results)
print(self._get_logo().format(color=self._color(self.distro), results=centered_results))
class BaseDisplay():
"""
All display classes should inherit this. It defigns several base functions that can be overwritten by any child classes
>>>import random
>>>class RandomNumber(BaseDisplay):
... key = 'Random Number'
... value = random.random() * 1000
...
>>>r = RandomNumber()
>>>print `r`
"""
key = None
value = None
def __repr__(self):
return '<{0}: key={1}, value={2}>'.format(self.__class__.__name__, self.key, self.value)
def get_key(self):
"""
Return the value of the class' key attribute. If classes wish to customise key generation,
they should override this method
"""
return self.key
def get_value(self):
"""
Return the value of the class' value attribute. If classes wish to customise value generation,
they should override this method
"""
return self.value
def key_value_pair(self):
"""
Returns a tuple of the key and value of the current display.
>>>disp = BaseDisplay()
>>>disp.key = 'Foo'
>>>disp.value = 'Bar'
>>>disp.key_value_pair()
('Foo', 'Bar')
"""
return (self.get_key(), self.get_value())
#class Hostname:
# def __init__(self):
#class Distro:
# def __init__(self):
#class Kernel:
# def __init__(self):
class Uptime(BaseDisplay):
key = 'Uptime'
def get_uptime(self):
fuptime = int(open('/proc/uptime').read().split('.')[0])
day = int(fuptime / 86400)
fuptime = fuptime % 86400
hour = int(fuptime / 3600)
fuptime = fuptime % 3600
minute = int(fuptime / 60)
return {'day': day, 'hour': hour, 'minute': minute}
def get_value(self):
uptime = self.get_uptime()
if uptime['day']:
value = '{day}{suffix}'.format(day=uptime['day'], suffix='s' if day > 1 else '')
else:
value = ''
value += '{hours}:{mins:02d}'.format(hours=uptime['hour'], mins=uptime['minute'])
return value
class WindowManager(BaseDisplay):
key = 'Window Manager'
def get_value(self):
wm = ''
for key in WM_DICT.keys():
if key in PROCESSES:
wm = WM_DICT[key]
break
return wm
class DesktopEnvironment(BaseDisplay):
key = 'Desktop Environment'
def get_value(self):
de = ''
for key in DE_DICT.keys():
if key in PROCESSES:
wm = WM_DICT[key]
break
return wm
def enviroment_variable(klass):
"""
Decorate classes with this decorator. Classes decorated with enviroment_variable will
have their __init__ function automaticly generated. This makes it very easy to write
a class that returns an enviroment variable.
>>>@enviroment_variable
...class Lang():
... key = 'Language'
... env = 'LANG'
...
>>>test = Lang()
>>>import os
>>>assert test.value == os.getenv('LANG')
"""
def get_value(self):
return os.getenv(self.env)
if hasattr(klass, 'key') and hasattr(klass, 'env'):
klass.get_value = get_value
else:
raise ArcheyException('Classes decorated with @enviroment_variable must have'
'key and env attributes')
return klass
@enviroment_variable
class Shell(BaseDisplay):
key = 'Shell'
env = 'SHELL'
@enviroment_variable
class Terminal(BaseDisplay):
key = 'Terminal'
env = 'TERM'
@enviroment_variable
class User(BaseDisplay):
key = 'User'
env = 'USER'
#class Packages():
# def __init__(self):
#class CPU():
# def __init__(self):
#class RAM():
# def __init__(self):
#class Disk():
# def __init__(self):
## TEST ## <<< TEMPORARY
def main():
out = Output()
out.append(Shell())
out.append(User())
out.append(Terminal())
out.append(Uptime())
out.append(WindowManager())
#out.append(DesktopEnvirornment())
out.output()
if __name__ == '__main__':
main()
|