def serial_write(ser=None, to_write=None): '''Basic Serial write function managed for Py2 and Py3 support.''' if ser is None: return None print_log(LOG.DEBUG, "Serial write (str):\n{}".format(to_write)) if is_running_with_py3(): to_write = to_write.encode() try: ser.write(to_write) except Exception as e: print_log(LOG.ERROR, str(e)) print_log(LOG.DEBUG, "Serial write (bytes):\n{}".format(to_write)) ser.flush()
def file_read_all_text(file_path): '''Read all text file content and return it in a string.''' read = "" # Check if file doesnt exists if not os_path.exists(file_path): print_log(LOG.ERROR, "File {} not found.".format(file_path)) # File exists, so open and read it else: try: if is_running_with_py3(): with open(file_path, "r", encoding="utf-8") as f: read = f.read() else: with open(file_path, "r") as f: read = f.read() except Exception as e: print_log( LOG.ERROR, "Can't open and read file {}. {}".format(file_path, str(e))) return read
def file_write(file_path, text=""): '''Write text to provided file.''' create_parents_dirs(file_path) # Determine if file exists and set open mode to write or append if not os_path.exists(file_path): print_log(LOG.INFO, "File {} not found, creating it...".format(file_path)) # Try to Open and write to file if is_running_with_py3(): try: with open(file_path, 'a', encoding="utf-8") as f: f.write(text) except Exception as e: print_log(LOG.ERROR, "Can't write to file {}. {}".format(file_path, str(e))) else: try: with open(file_path, 'a') as f: f.write(text) except Exception as e: print_log(LOG.ERROR, "Can't write to file {}. {}".format(file_path, str(e)))