-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
61 lines (47 loc) · 1.52 KB
/
utils.py
File metadata and controls
61 lines (47 loc) · 1.52 KB
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
"""A very mixed bag
Note-to-self: clean up
"""
import shlex
from collections import Counter
from subprocess import Popen, PIPE
def system_call(cmd, **kwargs):
"""
Wraps the rather ugly subprocess.Popen call.
`cmd` a string with the system call to be made, may also
contain pipes, for example:
system_call('ls -la | grep foo')
"""
cmds = cmd.split('|')
previous = None
for cmd in cmds:
stdin = getattr(previous, 'stdout', None)
stdout = kwargs.pop('stdout', PIPE)
stderr = kwargs.pop('stderr', PIPE)
previous = Popen(shlex.split(cmd),
stdin=stdin,
stdout=stdout,
stderr=stderr,
**kwargs)
out, err = previous.communicate()
if err:
raise OSError(err)
elif out:
return out.strip()
return ''
def setdefaultattr(obj, name, value):
""" This is for attribute what dict.setdefault is for dictionary keys """
return obj.__dict__.setdefault(name, value)
class IdGenerator(Counter):
"""Creates unique ids, optionally with prefix.
More or less like gensym in lisp """
def __call__(self, prefix=None):
self[prefix] += 1
if prefix is None:
return self[prefix]
else:
return prefix + str(self[prefix])
# TODO: do this in one pass, I still like the API though,
# kind of similar to divmod...
def minmax(it):
"""Return a tuple of the minimum and maximum value"""
return min(it), max(it)