cornsnake.util_proc

Running processes and opening Windows Explorer at a specified directory.

Documentation

  1"""
  2Running processes and opening Windows Explorer at a specified directory.
  3
  4[Documentation](http://docs.mrseanryan.cornsnake.s3-website-eu-west-1.amazonaws.com/cornsnake/util_proc.html)
  5"""
  6
  7import os
  8import subprocess
  9
 10from . import config
 11from . import util_log
 12from . import util_os
 13
 14logger = util_log.getLogger(__name__)
 15
 16
 17def _proc_print(message):
 18    """
 19    Logs the message using the logger and prints it if config.IS_VERBOSE is True.
 20
 21    Args:
 22    message (str): The message to log and possibly print.
 23    """
 24    logger.info(message)
 25    if config.IS_VERBOSE:
 26        print(message)
 27
 28
 29def _proc_print_debug(message):
 30    """
 31    Logs the message at debug level using the logger and prints it if config.IS_VERBOSE is True.
 32
 33    Args:
 34    message (str): The message to log and possibly print.
 35    """
 36    logger.debug(message)
 37    if config.IS_VERBOSE:
 38        print(message)
 39
 40
 41def is_process_running(process_name):
 42    """
 43    Checks if the given process (identified by program filename) is running.
 44
 45    Args:
 46    process_name (str): The filename of the process. For example 'notepad.exe'.
 47    """
 48    if util_os.is_windows():
 49        progs = str(subprocess.check_output("tasklist"))
 50        if process_name in progs:
 51            return True
 52        else:
 53            return False
 54    else:
 55        try:
 56            subprocess.check_output(["pgrep", process_name])
 57        except subprocess.CalledProcessError:
 58            return False
 59
 60
 61def run_process_and_get_output(
 62    path_to_proc, arguments, working_directory, output_errors=True
 63):
 64    """
 65    Executes a process with specified arguments and working directory, capturing the output.
 66
 67    Args:
 68    path_to_proc (str): The path to the process to execute.
 69    arguments (list): List of arguments for the process.
 70    working_directory (str): The working directory for the process.
 71    output_errors (bool): Flag to output errors. Default is True.
 72
 73    Returns:
 74    str: The standard output of the process.
 75
 76    Raises:
 77    RuntimeError: If the process returns a non-zero exit code.
 78    """
 79    _proc_print_debug(
 80        f"EXECUTING: '{path_to_proc} {arguments}' - at {working_directory}"
 81    )
 82
 83    pipes = subprocess.Popen(
 84        [path_to_proc] + arguments,
 85        stdout=subprocess.PIPE,
 86        stderr=subprocess.PIPE,
 87        cwd=working_directory,
 88    )
 89    std_out, std_err = pipes.communicate()
 90
 91    if not isinstance(std_out, str):
 92        std_out = std_out.decode()
 93    if not isinstance(std_err, str):
 94        std_err = std_err.decode()
 95
 96    if pipes.returncode != 0:
 97        # an error happened!
 98        err_msg = "%s. Code: %s" % (std_err.strip(), pipes.returncode)
 99        if output_errors:
100            print(err_msg)
101        else:
102            logger.debug(err_msg)
103        raise RuntimeError(err_msg, pipes.returncode)
104    elif len(std_err):
105        # return code is 0 (no error), but we may want to
106        # do something with the info on std_err
107        if output_errors:
108            print(std_err)
109        else:
110            logger.debug(std_err)
111
112    _proc_print_debug(f" >>> {std_out}")
113
114    return std_out
115
116
117def open_windows_explorer_at(path_to_dir):
118    """
119    Opens Windows Explorer or Mac Finder at the specified directory if the OS is Windows.
120
121    Args:
122    path_to_dir (str): The path to the directory to open in Windows Explorer.
123    """
124    if util_os.is_windows():
125        _proc_print(f"Opening Explorer at {path_to_dir}")
126        os.startfile(path_to_dir)
127        return
128    if util_os.is_mac():
129        _proc_print(f"Opening Finder at {path_to_dir}")
130        os.system(f"open {path_to_dir}")
131        return
132    else:
133        _proc_print(f"NOT opening {path_to_dir} - not Windows OS and not Mac")
logger = <Logger cornsnake.util_proc (INFO)>
def is_process_running(process_name):
42def is_process_running(process_name):
43    """
44    Checks if the given process (identified by program filename) is running.
45
46    Args:
47    process_name (str): The filename of the process. For example 'notepad.exe'.
48    """
49    if util_os.is_windows():
50        progs = str(subprocess.check_output("tasklist"))
51        if process_name in progs:
52            return True
53        else:
54            return False
55    else:
56        try:
57            subprocess.check_output(["pgrep", process_name])
58        except subprocess.CalledProcessError:
59            return False

Checks if the given process (identified by program filename) is running.

Args: process_name (str): The filename of the process. For example 'notepad.exe'.

def run_process_and_get_output(path_to_proc, arguments, working_directory, output_errors=True):
 62def run_process_and_get_output(
 63    path_to_proc, arguments, working_directory, output_errors=True
 64):
 65    """
 66    Executes a process with specified arguments and working directory, capturing the output.
 67
 68    Args:
 69    path_to_proc (str): The path to the process to execute.
 70    arguments (list): List of arguments for the process.
 71    working_directory (str): The working directory for the process.
 72    output_errors (bool): Flag to output errors. Default is True.
 73
 74    Returns:
 75    str: The standard output of the process.
 76
 77    Raises:
 78    RuntimeError: If the process returns a non-zero exit code.
 79    """
 80    _proc_print_debug(
 81        f"EXECUTING: '{path_to_proc} {arguments}' - at {working_directory}"
 82    )
 83
 84    pipes = subprocess.Popen(
 85        [path_to_proc] + arguments,
 86        stdout=subprocess.PIPE,
 87        stderr=subprocess.PIPE,
 88        cwd=working_directory,
 89    )
 90    std_out, std_err = pipes.communicate()
 91
 92    if not isinstance(std_out, str):
 93        std_out = std_out.decode()
 94    if not isinstance(std_err, str):
 95        std_err = std_err.decode()
 96
 97    if pipes.returncode != 0:
 98        # an error happened!
 99        err_msg = "%s. Code: %s" % (std_err.strip(), pipes.returncode)
100        if output_errors:
101            print(err_msg)
102        else:
103            logger.debug(err_msg)
104        raise RuntimeError(err_msg, pipes.returncode)
105    elif len(std_err):
106        # return code is 0 (no error), but we may want to
107        # do something with the info on std_err
108        if output_errors:
109            print(std_err)
110        else:
111            logger.debug(std_err)
112
113    _proc_print_debug(f" >>> {std_out}")
114
115    return std_out

Executes a process with specified arguments and working directory, capturing the output.

Args: path_to_proc (str): The path to the process to execute. arguments (list): List of arguments for the process. working_directory (str): The working directory for the process. output_errors (bool): Flag to output errors. Default is True.

Returns: str: The standard output of the process.

Raises: RuntimeError: If the process returns a non-zero exit code.

def open_windows_explorer_at(path_to_dir):
118def open_windows_explorer_at(path_to_dir):
119    """
120    Opens Windows Explorer or Mac Finder at the specified directory if the OS is Windows.
121
122    Args:
123    path_to_dir (str): The path to the directory to open in Windows Explorer.
124    """
125    if util_os.is_windows():
126        _proc_print(f"Opening Explorer at {path_to_dir}")
127        os.startfile(path_to_dir)
128        return
129    if util_os.is_mac():
130        _proc_print(f"Opening Finder at {path_to_dir}")
131        os.system(f"open {path_to_dir}")
132        return
133    else:
134        _proc_print(f"NOT opening {path_to_dir} - not Windows OS and not Mac")

Opens Windows Explorer or Mac Finder at the specified directory if the OS is Windows.

Args: path_to_dir (str): The path to the directory to open in Windows Explorer.