-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpython-csp
More file actions
607 lines (497 loc) · 16.4 KB
/
Copy pathpython-csp
File metadata and controls
607 lines (497 loc) · 16.4 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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
#!/usr/bin/env python
"""Interactive interpreter for python-csp, with online help.
Features:
* CSP primitives are imported automatically.
* CSP help is built in via. the 'info' command.
* History is saved between sessions in C{~/.csp-console-history}.
* Tab-completion can be used to complete keywords or variables.
Copyright (C) Sarah Mount, 2009.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
import atexit
import code
import os
import sys
__author__ = 'Sarah Mount <s.mount@wlv.ac.uk>'
__date__ = 'December 2008'
class _Printer(object):
"""Print documentation in twenty-line chunks.
Based on a class of the same name from the site.py module.
"""
MAXLINES = 20
def __init__(self, documentation):
self.__lines = documentation.split('\n')
self.__linecnt = len(self.__lines)
return
def __call__(self):
prompt = '\n*** Hit Return for more, or q (and Return) to quit: '
lineno = 0
while True:
try:
for i in range(lineno, lineno + self.MAXLINES):
print(self.__lines[i])
except IndexError:
break
else:
lineno += self.MAXLINES
key = None
while key not in ('', 'q', 'Q'):
key = input(prompt)
if key == 'q':
break
print()
class TabSafeCompleter(rlcompleter.Completer):
"""Enable safe use of Tab for either tab completion or nested scope.
"""
def complete(self, text, state):
if text == '':
return ['\t', None][state]
else:
return rlcompleter.Completer.complete(self, text, state)
class CSPConsole(code.InteractiveConsole):
"""python-csp interactive console with REPL.
Features:
* CSP channel server is started automatically.
* CSP primitives are imported automatically.
* CSP help is built in via. the 'info' command.
* History is saved between sessions in C{~/.csp-console-history}.
* Tab-completion can be used to complete keywords or variables.
"""
# From the docs of the readline module.
def __init__(self, locals=None, filename="<console>",
histfile=os.path.expanduser("~/.csp-console-history")):
code.InteractiveConsole.__init__(self)
self.init_history(histfile)
def init_history(self, histfile):
readline.parse_and_bind("tab: complete")
delims = ' \t\n`!@#$%^&*()-=+[{]}\\|;:,<>?'
readline.set_completer_delims(delims)
readline.set_completer(TabSafeCompleter().complete)
if hasattr(readline, "read_history_file"):
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(self.save_history, histfile)
def save_history(self, histfile):
readline.write_history_file(histfile)
def raw_input(self, *args):
line = code.InteractiveConsole.raw_input(self, *args)
if line == _INFOCSP:
_Printer(_cspinfo)()
return ''
elif line in _INFO:
_Printer(_INFO[line][1])()
return ''
elif line.startswith('info '):
print()
print('No info available on that topic. Try one of these:')
print()
print(_commands)
return ''
else:
return line
def _createBuiltinDocs():
"""Automatically create documentation for built-in process and guards.
This function iterates over the documentation strings in the
csp.builtins module and produces a larger documentation string
describing every name which does not begin with an underscore and
is not an imported module or CSP type.
"""
head = "\n*** python-csp: Info on built-in processes and guards. ***"
foot = "\n\n*** For more info, type 'info' at the prompt. ***\n"
docs = """ """
docstrings = {}
import csp.builtins
from csp.cspprocess import _CSPTYPES
cspnames = [klass.__name__ for klass in _CSPTYPES]
# Names imported by builtins
imports = ['copy', 'gc', 'inspect', 'operator', 'os', 'process', 'random',
'socket', 'sys', 'tempfile', 'threading', 'time', 'hmac',
'wraps', 'hashlib', 'psyco', 'pickle', 'logging', 'uuid']
exceptions = ['CorruptedData', 'NoGuardInAlt', 'ChannelPoison',
'ChannelAbort', 'ProcessSuspend']
baseclasses = ['CSPOpMixin', 'CSPProcess', 'Guard',
'Channel', 'FileChannel', 'process', 'NetworkChannel']
for name in dir(csp.builtins):
if (name in cspnames or name.startswith('_') or name in imports
or name in exceptions or name in baseclasses or name == 'DEBUG'
or name == 'SECURITY_ON'):
continue
qualname = 'csp.builtins' + '.' + name
if eval(qualname+'.__doc__'):
docstrings[name] = eval(qualname+'.__doc__')
del csp.cspprocess
names = list(docstrings.keys())
names.sort()
for name in names:
docs += '\n' + name + ':\n' + docstrings[name]
return head + '\n' + docs + foot
_INFOCSP = 'info'
_proc = """
*** python-csp: Info on processes. ***
There are two ways to create a new CSP process. Firstly, you can use
the @process decorator to convert a function definition into a CSP
Process. Once the function has been defined, calling it will return a
new CSPProcess object which can be started manually, or used in an
expression:
>>> @process
... def foo(n):
... print 'n:', n
...
>>> foo(100).start()
>>> n: 100
>>> foo(10) // (foo(20),)
n: 10
n: 20
<Par(Par-5, initial)>
>>>
Alternatively, you can create a CSPProcess object directly and pass a
function (and its arguments) to the CSPProcess constructor:
>>> def foo(n):
... print 'n:', n
...
>>> p = CSPProcess(foo, 100)
>>> p.start()
>>> n: 100
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_server = """
*** python-csp: Info on server processes. ***
A server process is one which runs in an infinite loop. You can create
a "normal" process which runs in an infinite loop, but by using server
processes you allow the python-csp debugger to correctly generate
information about your programs.
There are two ways to create a new CSP server process. Firstly, you
can use the @forever decorator to convert a generator into a CSPServer
object. Once the function has been defined, calling it will return a
new CSPServer object which can be started manually, or used in an
expression:
>>> @forever
... def integers():
... n = 0
... while True:
... print n
... n += 1
... yield
...
>>> integers().start()
>>> 0
1
2
3
4
5
...
KeyboardInterrupt
>>>
Alternatively, you can create a CSPServer object directly and pass a
function (and its arguments) to the CSPServer constructor:
>>> def integers():
... n = 0
... while True:
... print n
... n += 1
... yield
...
>>> i = CSPServer(integers)
>>> i.start()
>>> 0
1
2
3
4
5
...
KeyboardInterrupt
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_par = """
*** python-csp: Info on Par. ***
There are two ways to run processes in parallel. Firstly, given two
(or more) processes you can parallelize them with the // operator, like this:
>>> @process
... def foo(n):
... print 'n:', n
...
>>> foo(1) // (foo(2), foo(3))
n: 2
n: 1
n: 3
<Par(Par-5, initial)>
>>>
Notice that the // operator takes a CSPProcess on the left hand side
and a sequence of processes on the right hand side.
Alternatively, you can create a Par object which is a sort of CSP
process and start that process manually:
>>> p = Par(foo(100), foo(200), foo(300))
>>> p.start()
n: 100
n: 300
n: 200
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_seq = """
*** python-csp: Info on Seq. ***
There are two ways to run processes in sequence. Firstly, given two
(or more) processes you can sequence them with the > operator, like this:
>>> @process
... def foo(n):
... print 'n:', n
...
>>> foo(1) > foo(2) > foo(3)
n: 1
n: 2
n: 3
<Seq(Seq-14, initial)>
>>>
Secondly, you can create a Seq object which is a sort of CSP process
and start that process manually:
>>> s = Seq(foo(100), foo(200), foo(300))
>>> s.start()
n: 100
n: 200
n: 300
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_skip = """*** python-csp: Info on Skip. ***
Skip is a built in guard type that can be used with Alt
objects. Skip() is a default guard which is always ready and has no
effect. This is useful where you have a loop which calls select(),
pri_select() or fair_select() on an Alt object repeatedly and you do
not wish the select statement to block waiting for a channel write, or
other synchronisation. The following is a trivial example of an Alt
which uses Skip():
>>> alt = Alt(Skip())
>>> for i in xrange(5):
... print alt.select()
...
Skip
Skip
Skip
Skip
Skip
>>>
Where you have an Alt() object which mixes Skip() with other guard
types, be sure to complete all necessary channel reads or other
synchronisations, otherwise your code will hang.
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_timer = """*** python-csp: Info on timer guards. ***
Timer objects are a type of CSP guard, like Channel types and Skip
guards. Timer objects allow code to wait for a specific period of time
before synchronising on a timer event. This can be done in a number of
ways: either by sleeping for a period of time (similar to time.sleep
in the standard library), or by setting the timer to become selectable
(by an Alt object) after a specific period of time. For example:
>>> timer = Timer()
>>> timer.sleep(5) # sleep for 5 seconds
>>>
>>> alt = Alt(timer)
>>> timer.set_alarm(3) # become selectable 3 seconds from now
>>> alt.select() # will wait 3 seconds
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_alt = """
*** python-csp: Info on Alt. ***
python-csp process will often have access to several different
channels, or other guard types such as timer guards, and will have to
choose one of them to read from. For example, in a producer/consumer
or worker/farmer model, many producer or worker processes will be
writing values to channels and one consumer or farmer process will be
aggregating them in some way. It would be inefficient for the consumer
or farmer to read from each channel in turn, as some channels might
take longer than others. Instead, python-csp provides support for
ALTing (or ALTernating), which enables a process to read from the
first channel (or timer, or other guard) in a list to become ready.
The simplest way to choose between channels (or other guards) is to
use choice operator: "|", as in the example below:
>>> @process
... def send_msg(chan, msg):
... chan.write(msg)
...
>>> @process
... def choice(chan1, chan2):
... # Choice chooses a channel on which to call read()
... print chan1 | chan2
... print chan1 | chan2
...
>>> c1, c2 = Channel(), Channel()
>>> choice(c1, c2) // (send_msg(c1, 'yes'), send_msg(c2, 'no'))
yes
no
<Par(Par-8, initial)>
>>>
Secondly, you can create an Alt object explicitly, and call its
select() method to perform a channel read on the next available
channel. If more than one channel is available to read from, then an
available channel is chosen at random (for this reason, ALTing is
sometimes called "non-deterministic choice":
>>> @process
... def send_msg(chan, msg):
... chan.write(msg)
...
>>> @process
... def alt_example(chan1, chan2):
... alt = Alt(chan1, chan2)
... print alt.select()
... print alt.select()
...
>>> c1, c2 = Channel(), Channel()
>>> Par(send_msg(c1, 'yes'), send_msg(c2, 'no'), alt_example(c1, c2)).start()
yes
no
>>>
In addition to the select() method, which chooses an available guard
at random, Alt provides two similar methods, fair_select() and
pri_select(). fair_select() will choose not to select the previously
selected guard, unless it is the only guard available. This ensures
that no guard will be starved twice in a row. pri_select() will select
available channels in the order in which they were passed to the Alt()
constructor, giving a simple implementation of guard priority.
Lastly, Alt() can be used with the repetition operator (*) to create a
generator:
>>> @process
... def send_msg(chan, msg):
... chan.write(msg)
...
>>> @process
... def gen_example(chan1, chan2):
... gen = Alt(chan1, chan2) * 2
... print gen.next()
... print gen.next()
...
>>> c1, c2 = Channel(), Channel()
>>> Par(send_msg(c1, 'yes'), send_msg(c2, 'no'), gen_example(c1, c2)).start()
yes
no
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_channel = """
*** python-csp: Info on channels. ***
A CSP channel can be created with the Channel class:
>>> c = Channel()
>>>
Each Channel object should have a unique name in the network:
>>> print c.name
1ca98e40-5558-11df-8e5b-002421449824
>>>
The Channel can then be passed as an argument to any CSP process and
then be used either to read (using the .read() method) or to write
(using the .write() method). For example:
>>> @process
... def send(cout, data):
... cout.write(data)
...
>>> @process
... def recv(cin):
... print 'Got:', cin.read()
...
>>> c = Channel()
>>> send(c, 100) // (recv(c),)
Got: 100
<Par(Par-3, initial)>
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_poison = """
*** python-csp: Info on channel poisoning. ***
A set of communicating processes can be terminated by "poisoning" any
of the channels used by those processes. This can be achieved by
calling the poison() method on any channel. For example:
>>> @process
... def send5(cout):
... for i in xrange(5):
... print 'send5 sending:', i
... cout.write(i)
... time.sleep(random.random() * 5)
... return
...
>>> @process
... def recv(cin):
... for i in xrange(5):
... data = cin.read()
... print 'recv got:', data
... time.sleep(random.random() * 5)
... return
...
>>> @process
... def interrupt(chan):
... time.sleep(random.random() * 7)
... print 'Poisoning channel:', chan.name
... chan.poison()
... return
...
>>> doomed = Channel()
>>> send(doomed) // (recv(doomed), poison(doomed))
send5 sending: 0
recv got: 0
send5 sending: 1
recv got: 1
send5 sending: 2
recv got: 2
send5 sending: 3
recv got: 3
send5 sending: 4
recv got: 4
Poisoning channel: 5c906e38-5559-11df-8503-002421449824
<Par(Par-5, initial)>
>>>
*** For more info, type '%s' at the prompt. ***
""" % (_INFOCSP)
_builtin = _createBuiltinDocs()
# COMMAND -> (descriptor, docstring)
_INFO = {'info process':('processes', _proc),
'info server':('CSPServer', _server),
'info par':('Parallel', _par),
'info seq':('Sequence', _seq),
'info alt':('Alternative', _alt),
'info skip':('Skip', _skip),
'info timer':('Timer', _timer),
'info channel':('channels', _channel),
'info poison':('poisoning', _poison),
'info builtin':('built-ins', _builtin)}
_ban = """\npython-csp (c) 2008. Licensed under the GPL(v2).
Type "%s" for more information.
Press Ctrl-C to close the CSP channel server.
""" % (_INFOCSP)
_cspinfo = """
*** python-csp: general info ***
python-csp is an implementation of Hoare's Communicating Sequential
Processes in Python. For specific info on any aspect of CSP, use the
following:
"""
_commands = ""
for key in _INFO:
c = "For info on %s, type: \t%s\n" % (_INFO[key][0], key)
_commands += c
_cspinfo += _commands
if __name__ == '__main__':
c = CSPConsole(locals=locals())
# Don't expect the csp types to be available in locals()
c.push('from csp.cspprocess import *')
c.push('from csp.builtins import *')
c.interact(banner=_ban)