1

I am using subprocess in python 3 to use operating system commands (I am on ubuntu 18.04) and I was wondering if there was anyway to make make a custom error message while shell=True

import subprocess
command = str('wrong')
try:
   grepOut = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as grepexc:
    print("oops! wrong command")

When i run it I get:

/bin/sh: 1: wrong: not found
oops! wrong command

is there any way to remove the "/bin/sh: 1: wrong: not found" message and just have "oops! wrong command"?

Greer Page
  • 45
  • 1
  • 6
  • 1
    Possible duplicate of [subprocess.check\_output return code](https://stackoverflow.com/questions/23420990/subprocess-check-output-return-code) – Ronan Boiteau Jan 19 '19 at 23:24

1 Answers1

1

You can suppress the shell's error message by redirecting stderr, and insert your own by using check_output instead of call:

import subprocess
import os

command = str('wrong command')
devnull = open(os.devnull, 'w')

try:
    output = subprocess.check_output(command, shell=True, stderr=devnull)
except subprocess.CalledProcessError:
    print("oops! wrong command")
    output = ""

print(output)
Heath Raftery
  • 3,643
  • 17
  • 34