简体   繁体   中英

Python subprocess shell=true custom error message

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"?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM