def test_decode(): from spython.logger import decodeUtf8String out = decodeUtf8String(str("Hello")) assert isinstance(out, str) assert out == "Hello" out = decodeUtf8String(bytes(b"Hello")) assert isinstance(out, str) assert out == "Hello"
def run_command( cmd, sudo=False, capture=True, no_newline_regexp="Progess", quiet=False, sudo_options=None, environ=None, ): """run_command uses subprocess to send a command to the terminal. If capture is True, we use the parent stdout, so the progress bar (and other commands of interest) are piped to the user. This means we don't return the output to parse. Parameters ========== cmd: the command to send, should be a list for subprocess sudo: if needed, add to start of command no_newline_regexp: the regular expression to determine skipping a newline. Defaults to finding Progress capture: if True, don't set stdout and have it go to console. This option can print a progress bar, but won't return the lines as output. sudo_options: string or list of strings that will be passed as options to sudo """ cmd = _process_sudo_cmd(cmd, sudo, sudo_options) stdout = None if capture: stdout = subprocess.PIPE # Use the parent stdout and stderr process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=stdout, env=environ) lines = [] found_match = False for line in process.communicate(): if line: line = decodeUtf8String(line) lines.append(line) if re.search(no_newline_regexp, line) and found_match: if not quiet: sys.stdout.write(line) found_match = True else: if not quiet: sys.stdout.write(line) print(line.rstrip()) found_match = False output = {"message": lines, "return_code": process.returncode} return output
def println(self, output, quiet=False): '''print will print the output, given that quiet is not True. This function also serves to convert output in bytes to utf-8 Parameters ========== output: the string to print quiet: a runtime variable to over-ride the default. ''' if not self.quiet and not quiet: print(decodeUtf8String(output))
def write(self, stream, message): """write will write a message to a stream, first checking the encoding """ stream.write(decodeUtf8String(message))