324

我在 Ubuntu 上使用 eSpeak 并有一个 Python 2.7 脚本,可以打印并说出一条消息:

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

eSpeak 会产生所需的声音,但会因为一些错误(ALSA lib...,无套接字连接)而使外壳混乱,因此我无法轻松阅读之前打印的内容。退出代码为 0。

不幸的是,没有记录的选项可以关闭其冗长性,因此我正在寻找一种方法来仅在视觉上使其静音并保持打开的外壳清洁以进行进一步的交互。

我怎样才能做到这一点?

4

5 回答 5

509

对于 python >= 3.3,将输出重定向到 DEVNULL:

import os
import subprocess

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

对于 python <3.3,包括 2.7 使用:

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

它实际上与运行此 shell 命令相同:

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 中的新功能)。如果命令失败,它将抑制标准输出并引发异常。(它实际上返回标准输出的内容,因此如果需要,您可以稍后在程序中使用它。)示例:

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

在这里,您可以使用

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

从 Python3 开始,您不再需要打开 devnull 并且可以调用subprocess.DEVNULL

您的代码将按如下方式更新:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)
于 2018-07-23T21:56:35.113 回答
-7

为什么不使用 commands.getoutput() 代替?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)
于 2014-08-31T22:40:28.380 回答