Python Linux Command executor

twitter logo github logo ・1 min read

# IMPORTING LIBRARIES 
import subprocess
import shlex

def cmdExecutor(cliCmd):
    # COLLECT THE COMMAND AND SPLIT USING SHLEX
    cmd = shlex.split(cliCmd)
    # EXECUTE THE SUBPROCESS WITH COMMUNICATE()
    process,error = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
    print("Command executed successfully")
    # DECODE THE RESPONSE FROM THE SUBPROCESS TO UTF-8
    error = error.decode("utf-8")
    if(str(error)==None or str(error)==""):
        output="SUCCESS"
    else:
        output = "ERROR => "+str(error)
    return output
twitter logo DISCUSS (2)
markdown guide
 

Hi muTheTechie, I think you can simplify the error checking like this:

def cmdExecutor(cliCmd):
    cmd = shlex.split(cliCmd)
    process, error = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    print("Command executed successfully")
    if error:
      return f"ERROR => {error.decode('utf-8')}"
    else:
      return "SUCCESS"

you don't need to convert the error to a string

 
Classic DEV Post from Oct 31 '18

Lessons in my First Month of Active Blogging

Blogging actively has been an intense and rewarding process thus far, and I've taken this week to reflect on it!

muTheTechie profile image
Loving #opensource #AWS #python