forked from nmeier/simscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimscript.py
More file actions
279 lines (232 loc) · 8.61 KB
/
simscript.py
File metadata and controls
279 lines (232 loc) · 8.61 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
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
#!/usr/bin/env python
""" simscript main - automation of virtual inputs for simulators """
import sys,os,time,logging,tempfile,traceback,getopt,subprocess
def modulo(value,start,end):
if value!=value: #NaN check
return value
value = (value - start) % (end-start)
value = start+value if value>=0 else end+value
return value
class Script():
dir = os.path.abspath("scripts")
def __init__(self, name):
if not name: raise Exception("no such script %s" % name)
self.name = name if not name.endswith('.py') else name[:-3]
self.file = os.path.join(Script.dir, self.name+'.py')
if not self.exists(): raise Exception("script % doesn't exist" % name)
self.lastError = 0
self.lastCompile = 0
self.code = None
self.log = logging.getLogger(self.name)
def __str__(self):
return self.name
def exists(self):
return os.path.exists(self.file)
def modified(self):
return os.path.getmtime(self.file)
def run(self):
if self.modified()>self.lastCompile:
self.lastCompile = self.modified()
try:
with open(self.file, 'r') as handle:
self.code = compile(handle.read(), self.file, 'exec', dont_inherit=True)
except:
self.log.warning("compilation failed with %s" % traceback.format_exc())
self.code = None
# run script
try:
if self.code: exec(self.code)
except EnvironmentError as err:
if self.lastError < self.lastCompile:
self.log.warning(err)
self.lastError = self.lastCompile
except StopIteration:
pass
except Exception:
if self.lastError < self.lastCompile:
self.log.warning(traceback.format_exc())
self.lastError = self.lastCompile
def usage(detail=None):
print("Usage: %s -d|--debug [scriptname]" % os.path.split(sys.argv[0])[1])
if detail: print("***",detail)
return 1
class LogFile(logging.FileHandler):
def __init__(self):
self.error = 0
self.warn = 0
self.file = tempfile.NamedTemporaryFile(mode='w+', suffix='.log', prefix='simscript_', delete=False)
self._tail = None
logging.FileHandler.__init__(self, self.file.name, 'w+')
self.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
def __str__(self):
return "Log" if self.error==0 and self.warn == 0 else "Log (%d warnings, %d errors)" % (self.warn, self.error)
def emit(self, record):
if record.levelno==logging.WARN: self.warn += 1
elif record.levelno==logging.ERROR: self.error += 1
logging.FileHandler.emit(self, record)
def show(self):
self.hide()
# either deployed tail.exe, interpreting python (not pythonw) or fallback notepad
tail = 'notepad "%s"' % os.path.abspath(self.file.name)
if os.path.isfile("tail.exe"):
tail = 'tail.exe "%s"' % os.path.abspath(self.file.name)
elif 'python' in sys.executable:
python = sys.executable.replace('pythonw', 'python')
if os.path.isfile(python):
tail = '"%s" "%s" "%s"' % (python, os.path.abspath("tail.py"), os.path.abspath(self.file.name))
log.info("Launching %s", tail)
self._tail = subprocess.Popen(tail, creationflags=0x00000010) # CREATE_NEW_CONSOLE
self.reset()
def hide(self):
if not self._tail:
return
try:
self._tail.terminate()
except:
pass
self._tail = None
def reset(self):
self.warn = self.error = 0
class LoggerAsStream:
def __init__(self, logger, level):
self._logger = logger
self._level = level
self._buffer = ''
def write(self, buf):
for line in buf.splitlines(True):
if '\n' in line:
self._logger.log(self._level, self._buffer + line.rstrip())
self._buffer = ''
else:
self._buffer += line
def flush(self):
pass
def main(argv):
global script, active, log
# scan options
level = logging.INFO
hertz = 20
try:
opts, args = getopt.getopt(argv[1:], "h:d", ["hertz=","debug","help"])
for opt, arg in opts:
if opt in ("-d", "--debug"):
level = logging.DEBUG
if opt in ("-h", "--hertz"):
hertz = int(arg)
pass
if opt in ("--help"):
return usage()
except Exception as e:
return usage(str(e))
# setup logging
logging.basicConfig(level=level, stream=sys.stdout)
log = logging.getLogger(os.path.splitext(os.path.basename(argv[0]))[0])
logfile = LogFile()
log.info("Logging to %s" % logfile.file.name)
logging.getLogger().addHandler(logfile)
log.info("Python %s" % sys.version)
if sys.stderr:
sys.stderr = LoggerAsStream(logging.getLogger("STDOUT"), logging.INFO)
if sys.stdout:
sys.stdout = LoggerAsStream(logging.getLogger("STDERR"), logging.INFO)
# windows support?
try:
import windows
except:
log.info("Windows integration unavailable (e.g., System Tray Icon) - install http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32")
windows = None
# another instance running?
if windows and not windows.singleton():
log.info("instance already running - exiting")
return usage("already running")
# script to run
script = None
if len(args) > 1:
return usage()
elif len(args) == 1:
try:
script = Script(args[0])
except:
return usage("%s not found" % args[0])
else:
if not windows:
return usage()
try:
script = Script(windows.recall("script"))
except Exception as e:
log.debug("restoring recalled script failed %s" % e)
# ... load all modules
modules = []
sys.path.append("contrib")
sys.path.append("modules")
for py in os.listdir("modules"):
if not py.endswith("py"): continue
mod = os.path.splitext(py)[0]
try:
modules.append(__import__(mod))
except Exception as e:
log.warning("Couldn't initialize module %s: %s" % (mod, e) )
log.debug(traceback.format_exc())
# prep ui
def switch(name):
log.info("Switching to script %s" % name)
global script
script = Script(name)
windows.remember("script", script)
def bbye():
log.info("Quitting")
global active
active = False
def edit():
log.info("Edit")
subprocess.Popen("explorer %s" % Script.dir)
def actions():
actions = [("Quit", None, None, bbye), (logfile, None, None, logfile.show), ("Edit", None, None, edit)]
for handle in filter(lambda n: n.endswith('.py'), os.listdir("scripts")):
actions.append( (handle, None, script and os.path.basename(script.file)==handle, lambda f=handle: switch(f)) )
return actions
def sync(mod):
try:
method = mod.sync
except AttributeError:
return
method()
def exit(mod):
try:
method = mod.exit
except AttributeError:
return
method()
tray = windows.TrayIcon("SimScript", os.path.abspath('simscript.ico'), actions) if windows else None
# loop
active = True
while active:
try:
# take time
next = (time.clock()+(1.0/hertz))
# pump our threads messages
if windows: windows.pumpMessages(False)
# sync modules
for mod in modules:
sync(mod)
# run script
if script: script.run()
# check time
wait = next-time.clock()
if wait>=0 :
time.sleep(wait)
else:
log.info("%s executions took longer than next frequency (%dms>%dms)" % ( script, (1.0/hertz-wait)*1000, 1.0/hertz*1000))
except KeyboardInterrupt:
log.info("Interrupted")
active = False
# Cleanup
log.info("Exiting")
for mod in modules:
exit(mod)
tray.close()
logfile.hide()
# done
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))