Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def connect(self):
"""
Connects to Scratch.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.connect((self.host, self.port))
except socket.error as e:
self.connected = False
raise ScratchError(e)
self.connected = True
def _write(self, data):
"""
Writes string data out to Scratch
"""
total_sent = 0
length = len(data)
while total_sent < length:
try:
sent = self.socket.send(data[total_sent:].encode('UTF-8'))
except socket.error as e:
self.connected = False
raise ScratchError(e)
if sent == 0:
self.connected = False
raise ScratchConnectionError("Connection broken")
total_sent += sent
import array
import itertools
import socket
import struct
import sys
# For Scratch 3 handle long as int
if sys.version > '3':
long = int
class ScratchError(Exception): pass
class ScratchConnectionError(ScratchError): pass
class Scratch(object):
prefix_len = 4
broadcast_prefix_len = prefix_len + len('broadcast ')
sensorupdate_prefix_len = prefix_len + len('sensor-update ')
msg_types = set(['broadcast', 'sensor-update'])
def __init__(self, host='localhost', port=42001):
self.host = host
self.port = port
self.socket = None
self.connected = False
self.connect()
def _read(self, size):
"""
Reads size number of bytes from Scratch and returns data as a string
"""
data = b''
while len(data) < size:
try:
chunk = self.socket.recv(size-len(data))
except socket.error as e:
self.connected = False
raise ScratchError(e)
if chunk == '':
self.connected = False
raise ScratchConnectionError("Connection broken")
data += chunk
return data