def start(self): self.usb = UsbInterface() print( f"Connected to {self.usb.dev.product} - {self.usb.dev.serial_number}" ) self.read_buf = io.BytesIO() self.write_buf = io.BytesIO() self.read_file = io.IOBase() self.write_file = io.IOBase() self.read_file.close() self.write_file.close() self.buffers = []
def test_iobase(self): import io io.IOBase() class MyFile(io.BufferedIOBase): def __init__(self, filename): pass MyFile("file")
def __init__(self, name): self.port = "/dev/" + name self.node_name = name self.fd_port = io.IOBase() self.line = "" self.open_cnt = 0 self.read_iter = 0 self.is_loop_enabled = True threading.Thread.__init__(self, name=name)
def test_bad_read(self): """Check that we throw a useful exception on failure. """ # This should work both if the stream has a name... self.assertRaises(RuntimeError, retrieve_alerts, tempfile.NamedTemporaryFile()) # ...and if it doesn't. self.assertRaises(RuntimeError, retrieve_alerts, io.IOBase())
def test_is_seq(): no = [{'a': 1}, io.IOBase(), '123'] yes = [[1, 2], {1, 2}, (1, 2)] for obj in no: print(obj) assert not ps.is_seq(obj) for obj in yes: print(obj) assert ps.is_seq(obj)
def test_file_basic_sanity(): assert check_contracts(['file'], [io.IOBase()]) == {} with raises(ContractNotRespected): check_contracts(['file'], [1]) with raises(ContractNotRespected): check_contracts(['file'], [[]]) syntax_fail('file[]') syntax_fail('file[]()') syntax_fail('file()')
def getThreadStream(self): """ Get (or create) the file stream for the current thread. """ self._ready.wait(self.timeout) ident = currentThread().ident if ident not in self.threads: # First access from this thread. Open the file. fp = io.IOBase(*self.initArgs, **self.initKwargs) self.threads[ident] = fp return fp return self.threads[ident]
def test_stream_readonly(self): """test_stream_readonly Given a valid progress object When time is set to a valid integer And stream is set with read-only object Then it prints Error and redirects stream to stdout """ stream = io.IOBase() with progress(time=10, stream=stream) as prg: for _ in range(100): prg.tick() time.sleep(0.1)
def test_output_replace_is_seekable(self, tmp_path, dry_run): # Ideally, simply use sys.stdout as a non-seekable file object. However, pytest does # some special manipulation to sys.stdout that makes it seekable during unit tests. output_extract_file = io.IOBase() assert not output_extract_file.seekable() with pytest.raises(ValueError, match=r'output_extract must be a seekable object'): pin_image_references( str(tmp_path / 'manifests'), output_extract=output_extract_file, output_replace=io.StringIO(), dry_run=dry_run, )
def test_can_handle_variables_with_files(self): f = io.IOBase() self.assertEqual(get_files_from_variables({ 1: 2, 3: 4, 5: f }), ({ 1: 2, 3: 4, 5: None }, { 5: f }))
def __init__(self, name, acq): self.port = "/dev/" + name self.node_name = name self.fd_port = io.IOBase() self.error_cnt = 0 self.error_cnt_max = 0 self.cmd_rx_cnt = 0 self.ping_tx_cnt = 0 self.ping_rx_cnt = 0 self.line = "" self.open_cnt = 0 self.read_iter = 0 self.is_loop_enabled = True self.MAX_NODE_ERRORS = 10000 self.acq = acq threading.Thread.__init__(self, name=name)
def test_destructor(self): import io io.IOBase() record = [] class MyIO(io.IOBase): def __del__(self): record.append(1) def close(self): record.append(2) super(MyIO, self).close() def flush(self): record.append(3) super(MyIO, self).flush() MyIO() import gc; gc.collect() assert record == [1, 2, 3]
def test_remote(self): if not os.path.exists('remote.json'): print("Not found remote.json file so not tested for remote.") return with open('remote.json') as f: config = json.load(f) cmd = config['cmd'] pwd = config['pwd'] sys.stdin = io.IOBase() mock_r, mock_w = os.pipe() os.write(mock_w, 'mock text'.encode()) sys.stdin.fileno = lambda: mock_r sys.stdin.readable = lambda: True sys.stdin.read = lambda: pwd sys.argv[1:] = shlex.split(cmd) ret = iaw.main() if '--driver' in cmd: sys.argv[1:] = shlex.split(cmd.replace('--driver', '')) else: sys.argv[1:] = shlex.split(cmd + '--driver') ret = iaw.main()
def __init__(self, debug: bool = True) -> None: self.debug_ = debug self.prompt = "> " self.bindings = KeyBindings() self.stdout = StdoutProxy(sleep_between_writes=0.5) self.out = create_output(self.stdout) self.alt_out = io.IOBase() self.alt_out.write = self.out.write_raw self.alt_out.flush = self.out.flush self.log_handler = logging.StreamHandler(self.alt_out) log_format = "[{asctime} {levelname}:'{name}']: {message}" time_format = "%Y-%m-%d %H:%M:%S" self.log_formatter = pymine.api.console_log_formatter.CustomFormatter( fmt=log_format, datefmt=time_format, ) self.log_handler.setFormatter(self.log_formatter) self.logger = logging.getLogger() self.logger.addHandler(self.log_handler) if self.debug_: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) self.debug("Started Logger") self.ses = PromptSession( history=FileHistory("./.pmhist"), auto_suggest=AutoSuggestFromHistory(), key_bindings=self.bindings, mouse_support=True, output=self.out, )
#NOTE: remember for ctypesobj.contents creates a new python object #NOTE: ctypes.c_int._objects is memberdescriptor for object's __dict__ #NOTE: base class of all ctypes data types is non-public _CData try: # python 2.6 import fractions import number import io from io import StringIO as TextIO # built-in functions (CH 2) a['ByteArrayType'] = bytearray([1]) # numeric and mathematical types (CH 9) a['FractionType'] = fractions.Fraction() a['NumberType'] = numbers.Number() # generic operating system services (CH 15) a['IOBaseType'] = io.IOBase() a['RawIOBaseType'] = io.RawIOBase() a['TextIOBaseType'] = io.TextIOBase() a['BufferedIOBaseType'] = io.BufferedIOBase() a['UnicodeIOType'] = TextIO() # the new StringIO a['LoggingAdapterType'] = logging.LoggingAdapter(_logger, _dict) # pickle ok if HAS_CTYPES: a['CBoolType'] = ctypes.c_bool(1) a['CLongDoubleType'] = ctypes.c_longdouble() except ImportError: pass try: # python 2.7 import argparse # data types (CH 8) a['OrderedDictType'] = collections.OrderedDict(_dict)
def main(): special_paths = { x: Path("~", x).expanduser() for x in ["Desktop", "Documents"] } special_paths = OrderedDict( {x: y for x, y in special_paths.items() if y.exists()}) write_file = io.IOBase() write_file.close() read_file = io.IOBase() read_file.close() while True: while True: try: c = Command.read_cmd() print(f"Received command: {c.cmd_id}") break except usb.core.USBError: pass except KeyboardInterrupt: return 0 if not c.has_id(CommandId.WriteFile): write_file.close() if not c.has_id(CommandId.ReadFile): read_file.close() bufs = [] if c.has_id(CommandId.GetDriveCount): c.handler.add_drive("ROOT", "/") for arg in sys.argv[1:]: # Add arguments as drives folder = Path(arg).absolute() if folder.is_file(): folder = folder.parent c.handler.add_drive(folder.name, folder) c.write_base() c.write("I", len(c.handler.drives)) elif c.has_id(CommandId.GetDriveInfo): drive_idx = c.read("I") if drive_idx >= len(c.handler.drives): c.write_base(Command.ResultInvalidInput) else: info = c.handler.get_drive(drive_idx) c.write_base() c.write(info[1][1]) # Label c.write(info[0]) # Prefix #usage = shutil.disk_usage(info[1][0]) #c.write("II", usage.free & 0xFFFFFFFF, usage.total & 0xFFFFFFFF) # Not used by Goldleaf but still sent c.write("II", 0, 0) # Stubbed free/total space (not used by Goldleaf) elif c.has_id(CommandId.StatPath): path = c.read(Path) type = 0 file_size = 0 if path.is_file(): type = 1 file_size = path.stat().st_size elif path.is_dir(): type = 2 else: c.write_base(Command.ResultInvalidInput) c.send() continue c.write_base() c.write("IQ", type, file_size) elif c.has_id(CommandId.GetFileCount): path = c.read(Path) if path.is_dir(): files = [x for x in path.glob("*") if x.is_file()] c.write_base() c.write("I", len(files)) else: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.GetFile): path = c.read(Path) file_idx = c.read("I") if path.is_dir(): files = [x for x in path.glob("*") if x.is_file()] if file_idx >= len(files): c.write_base(Command.ResultInvalidInput) else: c.write_base() c.write(files[file_idx].name) else: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.GetDirectoryCount): path = c.read(Path) if path.is_dir(): dirs = [x for x in path.glob("*") if x.is_dir()] c.write_base() c.write("I", len(dirs)) else: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.GetDirectory): path = c.read(Path) dir_idx = c.read("I") if path.is_dir(): dirs = [x for x in path.glob("*") if x.is_dir()] if dir_idx >= len(dirs): c.write_base(Command.ResultInvalidInput) else: c.write_base() c.write(dirs[dir_idx].name) else: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.ReadFile): path = c.read(Path) offset, size = c.read("QQ") try: if read_file.closed: read_file = path.open("rb") read_file.seek(offset) bufs.append(read_file.read(size)) c.write_base() c.write("Q", size) except: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.WriteFile): path = c.read(Path) size = c.read("Q") data = c.read_raw(size) try: if write_file.closed: write_file = path.open("wb") write_file.write(data) c.write_base() except: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.Create): type = c.read("I") path = c.read(Path) if type == 1: try: path.touch() c.write_base() except: c.write_base(Command.ResultInvalidInput) elif type == 2: try: path.mkdir() c.write_base() except: c.write_base(Command.ResultInvalidInput) else: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.Delete): type = c.read("I") path = c.read(Path) try: if type == 1: os.remove(path) c.write_base() elif type == 2: shutil.rmtree(path) c.write_base() else: c.write_base(Command.ResultInvalidInput) except: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.Rename): type = c.read("I") path = c.read(Path) new_path = c.read(Path) try: path.rename(new_path) c.write_base() except: c.write_base(Command.ResultInvalidInput) elif c.has_id(CommandId.GetSpecialPathCount): c.write_base() c.write("I", len(special_paths)) elif c.has_id(CommandId.GetSpecialPath): spath_idx = c.read("I") if spath_idx >= len(special_paths): c.write_base(Command.ResultInvalidInput) else: info = list(special_paths.items())[spath_idx] c.write_base() c.write(info[0]) c.write(info[1]) elif c.has_id(CommandId.SelectFile): # Never used try: print() path = Path(input("Select file for Goldleaf: ")).absolute() c.write_base() c.write(path) except: c.write_base(Command.ResultInvalidInput) c.send() for buf in bufs: c.write_raw(buf) return 0
class StatusTab(TabbedPanel): # add tabs for display system information: system info tab, RTK tab, IMU tab path_info = ObjectProperty() filename_input = ObjectProperty() btn_logging = ObjectProperty() dataQueue = queue.Queue(maxsize=500) logging_status = False file_path = '' file_abs = '' fdLog = io.IOBase() def __init__(self, **kwargs): super(StatusTab, self).__init__(**kwargs) self.writeTrd = threading.Thread(target=self.do_writting, args=()) '''----other data storage ----''' self.UTCtime = ['00', '00', '00.000'] #RMC, GLL, GGA, ZDA, self.secCount = 0 self.pre_UTCtime = ['00', '00', '00.000'] self.GPStime = ['0000', '000000.000'] self.posLLA = ['00', '00.000000', 'N', '000', '00.000000', 'W'] #RMC, GLL, GGA self.velocity = '000.0' #RMC, VTG, self.heading = '000.0' #RMC, VTG, self.solution_status = [ '0', '0', ' ', '', '', '', '', '', '', '' ] # number of SV in solution, solution type, FAA mode, [3:9], GSA field:8-14 # 0:number of SV in solution- GSA, 1: solution_type - GSA, 2: FAA mode - RMC, GLL, VTG self.DOP = ['0.0', '0.0', '0.0'] #GSA self.date = ['00', '00', '0000'] #date from RMC ddmmyy, ZDA self.local_zone = ['', ''] #ZDA self.GGA = False self.RMC = False self.GLL = False self.GSA = False self.GSV = False self.VTG = False self.ZDA = False self.bind(size=self.update_fontsize) def UTCtoSecond(self, utc): second = utc[0] * 3600 + utc[1] * 60 + utc[2] return second def SecondtoUTC(self, second): if -86400 <= second < 0: second = 86400 + second else: return -1 min_sec = second % 3600 hr = (second - min_sec) / 3600 sec = min_sec % 60 min = (min_sec - sec) / 60 return [hr, min, sec] def update_info_label(self): self.info_label.text = ( """ [b]UTC time:[/b] {0}hr {1}min {2}sec [b]Position:[/b] {3}deg {4}min {5}, {6}deg {7}min {8} """ """[b]No. sv in sol:[/b] {9} [b]FAA mode:[/b] {18}\n""" """ [b]GPS time:[/b] {13}wk {14}sec [b]Ground vel:[/b] {15}[b]m/s[/b] [b]Heading:[/b] {16}deg """ """[b]Sol. type:[/b] {17} [b]DOP- P:[/b] {10}, [b]H:[/b] {11}, [b]V:[/b] {12}""" .format(self.UTCtime[0], self.UTCtime[1], self.UTCtime[2], self.posLLA[0], self.posLLA[1], self.posLLA[2], self.posLLA[3], self.posLLA[4], self.posLLA[5], self.solution_status[0], self.DOP[0], self.DOP[1], self.DOP[2], self.GPStime[0], self.GPStime[1], self.velocity, self.heading, self.solution_status[1], self.solution_status[2])) if self.secCount == 0: #utc = [int(self.UTCtime[0]), int(self.UTCtime[1]), float(self.UTCtime[2])] #temp_sec = self.UTCtoSecond(utc) #temp_utc = self.SecondtoUTC(temp_sec -1) self.pre_UTCtime[0] = self.UTCtime[0] self.pre_UTCtime[1] = self.UTCtime[1] self.pre_UTCtime[2] = self.UTCtime[2] self.secCount += 1 else: utc = [ int(self.UTCtime[0]), int(self.UTCtime[1]), float(self.UTCtime[2]) ] sec = self.UTCtoSecond(utc) utc0 = [ int(self.pre_UTCtime[0]), int(self.pre_UTCtime[1]), float(self.pre_UTCtime[2]) ] sec0 = self.UTCtoSecond(utc0) if sec - sec0 > 1: print('Larg time gap found: ' + str(sec - sec0)) print('current UTC: {0} {1} {2}; preveous UTC: {3} {4} {5}'. format(self.UTCtime[0], self.UTCtime[1], self.UTCtime[2], self.pre_UTCtime[0], self.pre_UTCtime[1], self.pre_UTCtime[2])) self.pre_UTCtime[0] = self.UTCtime[0] self.pre_UTCtime[1] = self.UTCtime[1] self.pre_UTCtime[2] = self.UTCtime[2] self.secCount += 1 def update_fontsize(self, instance, value): Clock.schedule_once( self.updateNow, 0) #call at next frame, so width is updated already #print('value: ' + str(value)) #print('instance info_label width: ' + str(instance.info_label.width)) #print('self info_label width: ' + str(self.info_label.width)) def updateNow(self, dt): #print('updateNow: self info_label width: ' + str(self.info_label.width)) if 14 <= self.info_label.width / 55 < 18: self.info_label.font_size = self.info_label.width / 55 elif self.info_label.width / 55 >= 18: self.info_label.font_size = 18 else: self.info_label.font_size = 14 #print('label font size: ' + str(self.info_label.font_size)) def dismiss_popup(self): self._popup.dismiss() def show_popup(self): if not self.logging_status: content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Select directiory/file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def load(self, path, filename): print('path: ' + path) print('select file: ' + filename) self.file_path = path + '\\' if filename == '': self.file_abs = path + '\\' else: rind = filename.rfind('\\') if rind > 0: fileonly = filename[rind + 1:len(filename)] else: fileonly = '' self.filename_input.text = fileonly self.file_abs = filename + '.log' self.path_info.text = ' Save data log at: ' + self.file_abs self.dismiss_popup() def do_filenameUpdate(self): if not self.logging_status: self.file_abs = self.file_path + self.filename_input.text + '.log' self.path_info.text = ' Save data log at: ' + self.file_abs def do_logging(self): if not self.logging_status: self.btn_logging.text = 'click to stop logging' print('open file : ' + self.file_abs) try: self.fdLog = open(self.file_abs, 'w') self.logging_status = True self.path_info.text = ' Save data at: ' + self.file_abs + ' ; logging now....' except: print('open file fail: ' + self.file_abs) if self.logging_status: if not self.writeTrd.is_alive(): try: self.writeTrd.start() except RuntimeError: # occurs if thread is dead self.writeTrd = threading.Thread( target=self.do_writting, args=()) self.writeTrd.start() else: self.stop_logging() def stop_logging(self): self.logging_status = False self.writeTrd.join() print('exit writting thread') self.fdLog.close() self.btn_logging.text = 'click to start logging' self.do_filenameUpdate() def do_writting(self): while self.logging_status: numberQ = self.dataQueue.qsize() print('current dataQueue sizeto write: ' + str(numberQ)) if numberQ > 0: for i in range(numberQ): newText = self.dataQueue.get() self.fdLog.write(newText) time.sleep(0.5) pass
import io from . import syntax_fail, good, fail good('file', io.IOBase()) fail('file', 1) fail('file', []) syntax_fail('file[]') syntax_fail('file[]()') syntax_fail('file()')