Python 3.x Python子进程shell=true自定义错误消息

Python 3.x Python子进程shell=true自定义错误消息,python-3.x,subprocess,ubuntu-18.04,Python 3.x,Subprocess,Ubuntu 18.04,我在Python3中使用subprocess来使用操作系统命令(我在ubuntu 18.04上),我想知道在shell=True时是否有自定义错误消息 import subprocess command = str('wrong') try: grepOut = subprocess.check_output(command, shell=True) except subprocess.CalledProcessError as grepexc: print("oops! wron

我在Python3中使用subprocess来使用操作系统命令(我在ubuntu 18.04上),我想知道在shell=True时是否有自定义错误消息

import subprocess
command = str('wrong')
try:
   grepOut = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as grepexc:
    print("oops! wrong command")
当我运行它时,我得到:

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

有没有办法删除“/bin/sh:1:error:not found”消息,只需执行“oops!error command”?

您可以通过重定向
stderr
来抑制shell的错误消息,并通过使用
check\u output
而不是
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)

可能重复感谢您如此快速的回复!尽管如此,我注意到当命令是一个实际的命令时,比如command='echo Ubuntu!'我没有得到任何结果。我测试了那个精确的场景,它对我来说很好,但现在我发现只有在REPL中才是正确的!我已更新了答案以解决此问题。感谢您的帮助!