Using a context here is much... smoother
exploited_language_features += 2; (I also exploit the mutability of the list-object here, yield j binds the list to the context, when the context is leaved execution continues and the modified j is written back)
This commit is contained in:
parent
797333e7ac
commit
84fdbfaff3
@ -5,6 +5,7 @@ import json
|
|||||||
import urllib.request, urllib.error, urllib.parse
|
import urllib.request, urllib.error, urllib.parse
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
import time
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
class BaseModule:
|
class BaseModule:
|
||||||
output = None
|
output = None
|
||||||
@ -69,29 +70,18 @@ class JSONIO:
|
|||||||
self.io.write(self.io.read())
|
self.io.write(self.io.read())
|
||||||
self.io.write(self.io.read())
|
self.io.write(self.io.read())
|
||||||
|
|
||||||
self._prefix = ""
|
@contextmanager
|
||||||
|
|
||||||
@property
|
|
||||||
def prefix(self):
|
|
||||||
prefix = self._prefix
|
|
||||||
self._prefix = ""
|
|
||||||
return prefix
|
|
||||||
|
|
||||||
@prefix.setter
|
|
||||||
def prefix(self, prefix):
|
|
||||||
self._prefix = prefix
|
|
||||||
|
|
||||||
def write(self, j):
|
|
||||||
self.io.write(self.prefix + json.dumps(j))
|
|
||||||
|
|
||||||
def read(self):
|
def read(self):
|
||||||
line, self.prefix = self.io.read(), ""
|
line, prefix = self.io.read(), ""
|
||||||
|
|
||||||
# ignore comma at start of lines
|
# ignore comma at start of lines
|
||||||
if line.startswith(","):
|
if line.startswith(","):
|
||||||
line, self.prefix = line[1:], ","
|
line, prefix = line[1:], ","
|
||||||
|
|
||||||
return json.loads(line)
|
j = json.loads(line)
|
||||||
|
yield j
|
||||||
|
|
||||||
|
self.io.write(prefix + json.dumps(j))
|
||||||
|
|
||||||
class I3statusHandler:
|
class I3statusHandler:
|
||||||
modules = []
|
modules = []
|
||||||
@ -112,13 +102,10 @@ class I3statusHandler:
|
|||||||
jio = JSONIO(self.io)
|
jio = JSONIO(self.io)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
j = jio.read()
|
with jio.read() as j:
|
||||||
|
for module in self.modules:
|
||||||
|
module.tick()
|
||||||
|
|
||||||
for module in self.modules:
|
output = module.output
|
||||||
module.tick()
|
if output:
|
||||||
|
j.insert(0, output)
|
||||||
output = module.output
|
|
||||||
if output:
|
|
||||||
j.insert(0, output)
|
|
||||||
|
|
||||||
jio.write(j)
|
|
||||||
|
Loading…
Reference in New Issue
Block a user