Skip to content

Instantly share code, notes, and snippets.

@roodee
Created February 14, 2023 09:13
Show Gist options
  • Save roodee/042db35ea1722bef2350959e8fa208cd to your computer and use it in GitHub Desktop.
Save roodee/042db35ea1722bef2350959e8fa208cd to your computer and use it in GitHub Desktop.
Use subprocess to run a shell script and log its console output
"""
Module providing one function, which calls a shell script and fetches it output for logging.
"""
from os.path import abspath, dirname, join
from os import listdir
import subprocess
import logging
SCRIPT_FILE_2_CALL = "shell_script_you_wanna_run.sh"
"""
Name of the file containing the shell script running whatever you want.
It is assumed to be located in the same directory as this module's file.
"""
def run_shell_script_using_subprocess_and_log_the_output() -> None :
"""
Provides function to run shell script file behind `SCRIPT_FILE_2_CALL`.
There is no return value.
"""
# Get the availabale logger
logger = logging.getLogger("")
# First: Get the current directory
cur_dir = dirname(abspath(__file__))
# Next: Build the location for the scriptfile
location_script_file_2_call = join(cur_dir, SCRIPT_FILE_2_CALL)
logger.info(f'Call script located at {location_script_file_2_call}')
# You can also make use of parameters to pass to your script
params = []
# Finally: Run the script and pass the parameters
try:
byte_output = subprocess.check_output(['bash', location_script_file_2_call, *params])
str_output = byte_output.decode('utf-8')
logger.info(str_output)
except subprocess.CalledProcessError as exc:
logger.error(exc.returncode, exc_info=True)
logger.error(exc.output, exc_info=True)
raise
@roodee
Copy link
Author

roodee commented Feb 14, 2023

Whenever you run a shell script and want to log the output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment