324

I'm using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message:

import subprocess
text = 'Hello World.'
print text
subprocess.call(['espeak', text])

eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib..., no socket connect) so i cannot easily read what was printed earlier. Exit code is 0.

Unfortunately there is no documented option to turn off its verbosity, so I'm looking for a way to only visually silence it and keep the open shell clean for further interaction.

How can I do this?

4

5 に答える 5

509

Python >= 3.3 の場合、出力を DEVNULL にリダイレクトします。

import os
import subprocess

retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL,
    stderr=subprocess.STDOUT)

2.7 を含む python <3.3 の場合:

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

これは、次のシェル コマンドを実行するのと事実上同じです。

retcode = os.system("echo 'foo' &> /dev/null")
于 2012-06-29T22:15:36.430 に答える
100

これがよりポータブルなバージョンです(楽しみのために、あなたの場合は必要ありません):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT

try:
    from subprocess import DEVNULL # py3k
except ImportError:
    import os
    DEVNULL = open(os.devnull, 'wb')

text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here
于 2012-06-30T01:02:41.797 に答える
33

を使用しますsubprocess.check_output(python 2.7 の新機能)。コマンドが失敗した場合、標準出力を抑制し、例外を発生させます。(実際には stdout の内容を返すので、後で必要に応じてプログラムで使用できます。) 例:

import subprocess
try:
    subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
    # Do something

次の方法で stderr を抑制することもできます。

    subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)

2.7 より前の場合は、

import os
import subprocess
with open(os.devnull, 'w')  as FNULL:
    try:
        subprocess._check_call(['espeak', text], stdout=FNULL)
    except subprocess.CalledProcessError:
        # Do something

ここで、 stderr を抑制することができます

        subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)
于 2016-07-14T21:32:28.720 に答える