__init__.py (6502:6c7d9e9b3c83) __init__.py (6654:4c84e771cca7)
1# Copyright (c) 2008 The Hewlett-Packard Development Company
1# Copyright (c) 2008-2009 The Hewlett-Packard Development Company
2# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the

--- 11 unchanged lines hidden (view full) ---

21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Nathan Binkert
28
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the

--- 11 unchanged lines hidden (view full) ---

22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27#
28# Authors: Nathan Binkert
29
30import os
31import re
32import sys
33
34import convert
35import jobfile
36
29from attrdict import attrdict, optiondict
30from code_formatter import code_formatter
37from attrdict import attrdict, optiondict
38from code_formatter import code_formatter
31from misc import *
32from multidict import multidict
33from orderdict import orderdict
39from multidict import multidict
40from orderdict import orderdict
34import jobfile
41from smartdict import SmartDict
35
42
36def print_list(items, indent=4):
43# define this here so we can use it right away if necessary
44def errorURL(prefix, s):
45 try:
46 import zlib
47 hashstr = "%x" % zlib.crc32(s)
48 except:
49 hashstr = "UnableToHash"
50 return "For more information see: http://www.m5sim.org/%s/%s" % \
51 (prefix, hashstr)
52
53# panic() should be called when something happens that should never
54# ever happen regardless of what the user does (i.e., an acutal m5
55# bug).
56def panic(fmt, *args):
57 print >>sys.stderr, 'panic:', fmt % args
58 print >>sys.stderr, errorURL('panic',fmt)
59 sys.exit(1)
60
61# fatal() should be called when the simulation cannot continue due to
62# some condition that is the user's fault (bad configuration, invalid
63# arguments, etc.) and not a simulator bug.
64def fatal(fmt, *args):
65 print >>sys.stderr, 'fatal:', fmt % args
66 print >>sys.stderr, errorURL('fatal',fmt)
67 sys.exit(1)
68
69class Singleton(type):
70 def __call__(cls, *args, **kwargs):
71 if hasattr(cls, '_instance'):
72 return cls._instance
73
74 cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
75 return cls._instance
76
77def addToPath(path):
78 """Prepend given directory to system module search path. We may not
79 need this anymore if we can structure our config library more like a
80 Python package."""
81
82 # if it's a relative path and we know what directory the current
83 # python script is in, make the path relative to that directory.
84 if not os.path.isabs(path) and sys.path[0]:
85 path = os.path.join(sys.path[0], path)
86 path = os.path.realpath(path)
87 # sys.path[0] should always refer to the current script's directory,
88 # so place the new dir right after that.
89 sys.path.insert(1, path)
90
91# Apply method to object.
92# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
93def applyMethod(obj, meth, *args, **kwargs):
94 return getattr(obj, meth)(*args, **kwargs)
95
96# If the first argument is an (non-sequence) object, apply the named
97# method with the given arguments. If the first argument is a
98# sequence, apply the method to each element of the sequence (a la
99# 'map').
100def applyOrMap(objOrSeq, meth, *args, **kwargs):
101 if not isinstance(objOrSeq, (list, tuple)):
102 return applyMethod(objOrSeq, meth, *args, **kwargs)
103 else:
104 return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq]
105
106def compareVersions(v1, v2):
107 """helper function: compare arrays or strings of version numbers.
108 E.g., compare_version((1,3,25), (1,4,1)')
109 returns -1, 0, 1 if v1 is <, ==, > v2
110 """
111 def make_version_list(v):
112 if isinstance(v, (list,tuple)):
113 return v
114 elif isinstance(v, str):
115 return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
116 else:
117 raise TypeError
118
119 v1 = make_version_list(v1)
120 v2 = make_version_list(v2)
121 # Compare corresponding elements of lists
122 for n1,n2 in zip(v1, v2):
123 if n1 < n2: return -1
124 if n1 > n2: return 1
125 # all corresponding values are equal... see if one has extra values
126 if len(v1) < len(v2): return -1
127 if len(v1) > len(v2): return 1
128 return 0
129
130def crossproduct(items):
131 if len(items) == 1:
132 for i in items[0]:
133 yield (i,)
134 else:
135 for i in items[0]:
136 for j in crossproduct(items[1:]):
137 yield (i,) + j
138
139def flatten(items):
140 while items:
141 item = items.pop(0)
142 if isinstance(item, (list, tuple)):
143 items[0:0] = item
144 else:
145 yield item
146
147# force scalars to one-element lists for uniformity
148def makeList(objOrList):
149 if isinstance(objOrList, list):
150 return objOrList
151 return [objOrList]
152
153def printList(items, indent=4):
37 line = ' ' * indent
38 for i,item in enumerate(items):
39 if len(line) + len(item) > 76:
40 print line
41 line = ' ' * indent
42
43 if i < len(items) - 1:
44 line += '%s, ' % item
45 else:
46 line += item
47 print line
154 line = ' ' * indent
155 for i,item in enumerate(items):
156 if len(line) + len(item) > 76:
157 print line
158 line = ' ' * indent
159
160 if i < len(items) - 1:
161 line += '%s, ' % item
162 else:
163 line += item
164 print line
165
166def readCommand(cmd, **kwargs):
167 """run the command cmd, read the results and return them
168 this is sorta like `cmd` in shell"""
169 from subprocess import Popen, PIPE, STDOUT
170
171 if isinstance(cmd, str):
172 cmd = cmd.split()
173
174 no_exception = 'exception' in kwargs
175 exception = kwargs.pop('exception', None)
176
177 kwargs.setdefault('shell', False)
178 kwargs.setdefault('stdout', PIPE)
179 kwargs.setdefault('stderr', STDOUT)
180 kwargs.setdefault('close_fds', True)
181 try:
182 subp = Popen(cmd, **kwargs)
183 except Exception, e:
184 if no_exception:
185 return exception
186 raise
187
188 return subp.communicate()[0]