Module util
[hide private]
[frames] | no frames]

Source Code for Module util

  1  # -*- coding: utf-8 -*- 
  2   
  3  ############################################################################ 
  4  # util.py 
  5  # 
  6  # Main Utilities class for MOCOP. 
  7  # 
  8  # (C) 2008 Likya Software Ltd. 
  9  ############################################################################ 
 10   
 11  import os, sys, cPickle, zlib, time, random, fnmatch, tempfile 
 12   
 13   
 14  from twisted.spread import pb 
 15  from twisted.spread.util import StringPager 
 16  from twisted.internet import defer, reactor 
17 18 19 -class Util(object):
20 ''' 21 General utility functions shared between client and server. 22 ''' 23 FUNC_TESTER_TYPE_LOG = 'log' 24 FUNC_TESTER_TYPE_STDOUT = 'stdout' 25 FUNC_TESTER_TYPE_STDERR = 'stderr' 26 FUNC_TESTER_LOG_PREFIX = '-=|' 27 FUNC_TESTER_ASSERT_ERROR = '[FUNC.TEST] ASSERT ERROR:' 28 FUNC_TESTER_OTHER_ERROR = '[FUNC.TEST] OTHER ERROR:' 29 FUNC_TESTER_ASSERT_SUCCESS = '[FUNC.TEST] ASSERT SUCCESS:' 30 FUNC_TESTER_RESULT_FAILED = '[FUNC.TEST] FAILED:' 31 FUNC_TESTER_RESULT_PASSED = '[FUNC.TEST] PASSED:' 32 FUNC_TESTER_NORMAL_LOG = '[FUNC.TEST] LOG:' 33 34 WIN_DELETE_CHR = u'\x7f' 35 WIN_BACKSPACE_SCANCODE = 14 36 37 @staticmethod
38 - def flushedOutput(aStr):
39 ''' 40 Writes the string C{aStr} to the standart output and flushes 41 standart output 42 ''' 43 print aStr 44 sys.stdout.flush() 45 time.sleep(0.01)
46 47 @staticmethod
48 - def tempFileName():
49 ''' 50 Returns a temporary file name. Does not create the file, just 51 returns a unique file name in the system temporary directory. 52 53 @return: A unique temporary file name 54 @rtype: str 55 ''' 56 parts = [] 57 # Zaman kısmı 58 parts.append("%016x" % (long(time.time() * os.getpid()))) 59 # random part 60 parts.append(("%08x" % (random.random() * sys.maxint))[:8]) 61 return os.path.join(tempfile.gettempdir(), ''.join(parts))
62 63 @staticmethod
64 - def dumps(obj):
65 ''' 66 Given object I{obj}, first pickles than compresses. 67 68 @param obj: Any object that can be pickled. 69 ''' 70 return zlib.compress(cPickle.dumps(obj, 2))
71 72 @staticmethod
73 - def loads(asciiStr):
74 ''' 75 Expands the given string then unpickles. Returns the object 76 unpickled. 77 78 @param asciiStr: String that was created by a call to L{dumps} 79 ''' 80 return cPickle.loads(zlib.decompress(asciiStr))
81 82 @staticmethod
83 - def uniq():
84 ''' 85 Returns a uniq string of hexadecimal characters. 86 ''' 87 # random part 88 retval = ("%08x" % (random.random() * 2147483647))[:8] 89 retval += ("%08x" % (random.random() * 2147483647))[:8] 90 return retval
91 92 @staticmethod
93 - def logToFile(message, file='log.txt', prms='a'):
94 ''' 95 Appends the given message to the file. 96 97 @param file: The file to append the message 98 @param message: The message to append to file 99 ''' 100 f = open(file, prms) 101 f.write('LOG: %s %s\n' % (time.strftime('%H:%M %d-%m-%Y'), message)) 102 f.close()
103 104 @staticmethod
105 - def iglobRecursively(root='.', pattern="*"):
106 ''' 107 Locate all files matching supplied filename pattern in and below 108 supplied root directory. Returns a generator. 109 ''' 110 for path, dirs, files in os.walk(root): 111 for filename in fnmatch.filter(files, pattern): 112 yield os.path.join(path, filename)
113 114 @staticmethod
115 - def globRecursively(root='.', pattern="*"):
116 ''' 117 Locate all files matching supplied filename pattern in and below 118 supplied root directory. Returns result as a list. 119 ''' 120 return list(Util.iglobRecursively(root, pattern))
121 122 @staticmethod
123 - def logToFile(msg, fileName='/home/dia/log.txt'):
124 open(fileName, 'ab').write("%s\n" % msg)
125 126 @staticmethod
127 - def deferredSleep(seconds, deferer=None):
128 ''' 129 Non-blocking sleep 130 ''' 131 if deferer is None: 132 deferer = defer.Deferred() 133 reactor.callLater(seconds, Util.deferredSleep, seconds, deferer) 134 135 else: 136 deferer.callback(None) 137 138 return deferer
139 140 @staticmethod
141 - def escapeString(aStr):
142 ''' 143 Escapes the given string. Suitable for producing script files. 144 ''' 145 return aStr.replace("\\", "\\\\") \ 146 .replace("\n", "\\n") \ 147 .replace("\r", "\\r") \ 148 .replace("\t", "\\t") \ 149 .replace("'", "\\'") \ 150 .replace("\b", "\\b")
151 152 @staticmethod
153 - def isPrintable(aChr):
154 ''' 155 Returns True if the given character is printable, False otherwise 156 Escapes the given string. Suitable for producing script files. 157 ''' 158 if not aChr: 159 return False 160 elif aChr == Util.WIN_DELETE_CHR: 161 return False 162 elif Util.escapeString(aChr)[0] == '\\': 163 return False 164 else: 165 return True
166
167 168 -class MCResultsPager(StringPager):
169 ''' 170 Result pager class for sending large objects. 171 '''
172 - def __init__(self, collector, string):
173 self._atFirstPage = True 174 self._deferred = defer.Deferred() 175 StringPager.__init__(self, collector, string, chunkSize=65536, callback=self.done)
176
177 - def sendNextPage(self):
178 StringPager.sendNextPage(self)
179
180 - def done(self):
181 self._deferred.callback(self.collector)
182
183 - def wait(self):
184 return self._deferred
185
186 187 -class MCPageCollector(pb.Referenceable):
188 ''' 189 Result collector class for retrieving large objects. 190 '''
191 - def __init__(self):
192 self.pages = []
193
194 - def remote_gotPage(self, page):
195 self.pages.append(page)
196
197 - def remote_endedPaging(self):
198 pass
199