#!/usr/bin/env python r""" This module provides command execution functions such as cmd_fnc and cmd_fnc_u. """ import sys import subprocess robot_env = 1 try: from robot.libraries.BuiltIn import BuiltIn except ImportError: robot_env = 0 import gen_print as gp import gen_valid as gv import gen_misc as gm if robot_env: import gen_robot_print as grp ############################################################################### def cmd_fnc(cmd_buf, quiet=None, test_mode=None, debug=0, print_output=1, show_err=1): r""" Run the given command in a shell and return the shell return code. Description of arguments: cmd_buf The command string to be run in a shell. quiet Indicates whether this function should run the pissuing() function prints an "Issuing: " to stdout. test_mode If test_mode is set, this function will not actually run the command. debug If debug is set, this function will print extra debug info. print_output If this is set, this function will print the stdout/stderr generated by the shell command. show_err If show_err is set, this function will print a standardized error report if the shell command returns non-zero. """ quiet = int(gm.global_default(quiet, 0)) test_mode = int(gm.global_default(test_mode, 0)) if debug: gp.print_vars(cmd_buf, quiet, test_mode, debug) err_msg = gv.svalid_value(cmd_buf) if err_msg != "": raise ValueError(err_msg) if not quiet: gp.pissuing(cmd_buf, test_mode) if test_mode: return 0, "" sub_proc = subprocess.Popen(cmd_buf, bufsize=1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out_buf = "" for line in sub_proc.stdout: out_buf += line if not print_output: continue if robot_env: grp.rprint(line) else: sys.stdout.write(line) if print_output and not robot_env: sys.stdout.flush() sub_proc.communicate() shell_rc = sub_proc.returncode if shell_rc != 0 and show_err: if robot_env: grp.rprint_error_report("The prior command failed.\n" + gp.sprint_var(shell_rc, 1)) else: gp.print_error_report("The prior command failed.\n" + gp.sprint_var(shell_rc, 1)) return shell_rc, out_buf ############################################################################### ############################################################################### def cmd_fnc_u(cmd_buf, quiet=None, debug=None, print_output=1, show_err=1): r""" Call cmd_fnc with test_mode=0. See cmd_fnc (above) for details. Note the "u" in "cmd_fnc_u" stands for "unconditional". """ return cmd_fnc(cmd_buf, test_mode=0, quiet=quiet, debug=debug, print_output=print_output, show_err=show_err) ###############################################################################