-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrioscripter.py
442 lines (383 loc) · 11 KB
/
trioscripter.py
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
#coding: utf-8
'''
# Installation
`pip install` dependencies:
* `trio`
* `asks`
* `contextvars` (before Python 3.7)
Overlay view dependencies:
* overlay
* gestures
'''
# Trio workarounds for Pythonista, see https://github.com/python-trio/trio/issues/684
import warnings, signal
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import trio
import asks
asks.init('trio')
signal.signal(signal.SIGINT, signal.SIG_DFL)
#trio._core._run._MAX_TIMEOUT = 1.0
import functools, types, inspect, time
from overlay import Overlay, AppWindows
import ui, objc_util
class ValueNotDefinedYet(Exception):
def __init__(self):
super().__init__('Value has not been returned yet. Did you forget to yield?')
class GeneratorValueWrapper():
def __init__(self, gen):
self.gen = gen
self._value = ValueNotDefinedYet()
@property
def value(self):
if isinstance(self._value, Exception):
raise Exception(str(self._value)) from self._value
else:
return self._value
def cancel(self):
trio._scripter.cancel(self)
def script(func):
'''
Decorator for the async scripts.
Scripts piggyback on the trio event loop.
Script actions execute in parallel until the next `yield` statement.
New scripts suspend the execution of the parent script until all the parallel scripts have
completed, after which parent script execution is resumed.
'''
@functools.wraps(func)
def wrapper(*args, **kwargs):
scr = trio._scripter
if inspect.isgeneratorfunction(func):
gen = func(*args, **kwargs)
elif inspect.iscoroutinefunction(func):
gen = func(*args, **kwargs)
gen = scr._async_handler(gen)
return gen
else:
def gen_wrapper(func, *args, **kwargs):
func(*args, **kwargs)
yield
gen = gen_wrapper(func, *args, **kwargs)
scr.parent_gens[gen] = scr.current_gen
if scr.current_gen != 'root':
scr.standby_gens.setdefault(scr.current_gen, set())
scr.standby_gens[scr.current_gen].add(gen)
scr.deactivate.add(scr.current_gen)
scr.activate.add(gen)
scr.wake_up.set()
value_wrapper = GeneratorValueWrapper(gen)
scr.value_by_gen[gen] = value_wrapper
return value_wrapper
return wrapper
'''
def extract(gen):
"Extracts the returned value of a completed script. Raises an Exception if the value is not available."
#loop = asyncio.get_event_loop()
#scr = loop._scripter
scr = trio._scripter
try:
value = scr.value_by_gen[gen]
except KeyError:
raise Exception('No value available. Remember to return a value from the script and yield before calling extract. ')
if isinstance(value, Exception):
raise Exception('Task raised an exception:' + str(value.args)) from value
else:
return value
'''
class Scripter():
default_duration = 0.5
def __init__(self):
self.cancel_all()
#loop = asyncio.get_event_loop()
#self._session = aiohttp.ClientSession(loop=loop)
def end_all(self):
if not self._session.closed:
self._session.close()
async def update(self, nursery):
'''
Main Scripter animation loop handler, called by the Puthonista UI loop and never by your
code directly.
This method:
* Activates all newly called scripts and suspends their parents.
* Calls all active scripts, which will run to their next `yield` or until completion.
* As a convenience feature, if a `yield` returns `'wait'` or a specific duration,
kicks off a child `timer` script to wait for that period of time.
* Cleans out completed scripts.
* Resumes parent scripts whose children have all completed.
* Sets `update_interval` to 0 if all scripts have completed.
'''
run_at_least_once = True
while run_at_least_once or len(self.activate) > 0 or len(self.deactivate) > 0:
run_at_least_once = False
for gen in self.activate:
self.active_gens.add(gen)
for gen in self.deactivate:
self.active_gens.remove(gen)
self.activate = set()
self.deactivate = set()
gen_to_end = []
for gen in self.active_gens:
self.current_gen = gen
wait_time = self.should_wait.pop(gen, None)
if wait_time is not None:
timer(wait_time)
else:
yielded = None
try:
yielded = next(gen)
except StopIteration as stopped:
if gen not in self.deactivate:
gen_to_end.append(gen)
self.value_by_gen[gen]._value = stopped.value
del self.value_by_gen[gen]
if yielded is not None:
if yielded == 'wait':
yielded = self.default_duration
if type(yielded) in [int, float]:
self.should_wait[gen] = yielded
elif type(yielded) is tuple:
coro, queue = yielded
async def async_runner(coro, queue):
try:
value = await coro
queue.put_nowait(value)
except Exception as e:
queue.put_nowait(e)
nursery.start_soon(async_runner, coro, queue)
self.current_gen = 'root'
self.time_paused = 0
for gen in gen_to_end:
self.active_gens.remove(gen)
parent_gen = self.parent_gens[gen]
del self.parent_gens[gen]
if parent_gen != 'root':
self.standby_gens[parent_gen].remove(gen)
if len(self.standby_gens[parent_gen]) == 0:
self.activate.add(parent_gen)
del self.standby_gens[parent_gen]
return len(self.active_gens) + len(self.standby_gens) > 0
# self.update_interval = 0.0
# self.running = False
def cancel(self, script):
''' Cancels any ongoing animations and
sub-scripts for the given script. '''
to_cancel = set()
to_cancel.add(script)
parent_gen = self.parent_gens[script]
if parent_gen != 'root':
self.standby_gens[parent_gen].remove(script)
if len(self.standby_gens[parent_gen]) == 0:
self.active_gens.add(parent_gen)
del self.standby_gens[parent_gen]
found_new = True
while found_new:
new_found = set()
found_new = False
for gen in to_cancel:
if gen in self.standby_gens:
for child_gen in self.standby_gens[gen]:
if child_gen not in to_cancel:
new_found.add(child_gen)
found_new = True
for gen in new_found:
to_cancel.add(gen)
for gen in to_cancel:
if gen == self.current_gen:
self.current_gen = parent_gen
del self.value_by_gen[gen]
del self.parent_gens[gen]
self.activate.discard(gen)
self.deactivate.discard(gen)
self.active_gens.discard(gen)
if gen in self.standby_gens:
del self.standby_gens[gen]
def cancel_all(self):
''' Initializes all internal structures.
Used at start and to cancel all running scripts.
'''
self.current_gen = 'root'
self.should_wait = {}
self.parent_gens = {}
self.value_by_gen = {}
self.active_gens = set()
self.standby_gens = {}
self.activate = set()
self.deactivate = set()
#self.running = False
@script
def _async_handler(self, coro):
queue = trio.Queue(1)
yield (coro, queue)
while True:
try:
return queue.get_nowait()
except trio.WouldBlock:
pass
yield
async def _scripter_runner(self, nursery):
while True:
if not await self.update(nursery):
if not self.forever: break
with trio.move_on_after(1):
await self.wake_up.wait()
self.wake_up.clear()
await trio.sleep(0)
async def _runner(self):
#loop = asyncio.get_event_loop()
#i = 0
if self.start_script:
self.start_script()
async with trio.open_nursery() as nursery:
if self.hud:
self.overlay = self.open_overlay()
nursery.start_soon(self._scripter_runner, nursery)
print('end')
#self.end_all()
def close_down(self):
task = trio.hazmat.current_root_task()
print(dir(task))
@objc_util.on_main_thread
def open_overlay(self):
view = ui.View(name='Trio')
view.frame = (0, 0, 200, 1)
view.flex = 'WH'
view.background_color = 'white'
o = Overlay(content=view, parent=AppWindows.root())
o.close_callback = self.close_down
return o
@classmethod
def run(cls, start_script=None, forever=False, hud=False):
print('starting')
trio._scripter = scr = Scripter()
scr.forever = forever
scr.hud = hud
scr.start_script = start_script
scr.wake_up = trio.Event()
trio.run(scr._runner)
print('done')
@classmethod
def bootstrap(cls):
scr = Scripter()
loop = asyncio.get_event_loop()
loop._scripter = scr
print('starting')
loop.call_soon(scr._runner())
print('done')
@script
def timer(duration=None, action=None):
''' Acts as a wait timer for the given
duration in seconds. Optional action
function is called every cycle. '''
duration = duration or 0.3
start_time = time.time()
dt = 0
while dt < duration:
if action: action()
yield
dt = time.time() - start_time
@script
async def get(*args, **kwargs):
response = await asks.get(*args, **kwargs)
return response
@script
async def post(*args, **kwargs):
response = await asks.post(*args, **kwargs)
return response
if __name__ == '__main__':
sites = '''youtube.com
facebook.com
baidu.com
wikipedia.org
reddit.com
yahoo.com
google.co.in
amazon.com
twitter.com
sohu.com
instagram.com
vk.com
jd.com
sina.com.cn
weibo.com
yandex.ru
google.co.jp
google.co.uk
list.tmall.com
google.ru
google.com.br
netflix.com
google.de
google.com.hk
twitch.tv
google.fr
linkedin.com
yahoo.co.jp
t.co
microsoft.com
bing.com
office.com
xvideos.com
google.it
google.ca
mail.ru
ok.ru
google.es
pages.tmall.com
msn.com
google.com.tr
google.com.au
whatsapp.com
spotify.com
google.pl
google.co.id
xhamster.com
google.com.ar
xnxx.com
google.co.th
Naver.com
sogou.com
accuweather.com
goo.gl
sm.cn
googleweblight.com'''.splitlines()
import datetime
s = asks.Session(connections=100)
async def grabber(site):
r = await s.get('https://'+site, timeout=5)
content = r.text
#print(site)
async def main():
async with trio.open_nursery() as n:
for site in sites:
n.start_soon(grabber, site)
@script
def retrieve_all():
for site in sites:
worker(site)
print(site)
@script
def worker(site):
result = get('https://'+site, timeout=5)
yield
content = result.value.text
def baseline_requests():
import requests
for site in sites:
print(site)
url = 'https://'+site
try:
resp = requests.get(url, timeout=(5,5))
content = resp.text
except Exception as e:
print(str(e))
@script
def simple_test():
print('hello')
#yield # inserted automatically
start = datetime.datetime.now()
#baseline_requests()
#trio.run(main)
#Scripter.run(lean_retriever)
Scripter.run(simple_test, forever=True, hud=True)
duration = datetime.datetime.now() - start
print(len(sites), 'sites in', str(duration))