如何隐藏子进程的输出
- 2024-12-04 08:56:00
- admin 原创
- 135
问题描述:
我在 Ubuntu 上使用 eSpeak,并且有一个可以打印和读出消息的 Python 2.7 脚本:
import subprocess
text = 'Hello World.'
print text
subprocess.call(['espeak', text])
eSpeak 产生了所需的声音,但由于一些错误(ALSA lib...,没有套接字连接)而使 shell 变得混乱,因此我无法轻松读取先前打印的内容。退出代码为 0。
不幸的是,没有记录的选项可以关闭它的详细程度,所以我正在寻找一种仅在视觉上使其静音并保持打开的外壳清洁以便进行进一步的交互的方法。
我怎样才能做到这一点?
请参阅不带输出的 Python os.system来了解具体方法os.system
- 尽管现代代码通常应该使用subprocess
库。
解决方案 1:
对于 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")
解决方案 2:
这是一个更便携的版本(只是为了好玩,在你的情况下没有必要):
#!/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
解决方案 3:
使用subprocess.check_output
(python 2.7 中的新功能)。它将捕获 stdout 作为函数的返回值,这样既可以防止将其发送到标准输出,又可以供您以编程方式使用。例如subprocess.check_call
,如果命令失败,这会引发异常,这通常是您从控制流角度想要的。示例:
import subprocess
try:
output = subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
# Handle failed call
您还可以使用以下方式抑制 stderr:
output = subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)
对于 2.7 之前的版本,使用
import os
import subprocess
with open(os.devnull, 'w') as FNULL:
try:
output = subprocess._check_call(['espeak', text], stdout=FNULL)
except subprocess.CalledProcessError:
# Handle failed call
在这里,你可以使用以下方法抑制 stderr
output = subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)
解决方案 4:
从 Python3 开始,您不再需要打开 devnull 并可以调用subprocess.DEVNULL。
您的代码将被更新如下:
import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)
解决方案 5:
为什么不使用commands.getoutput()呢?
import commands
text = "Mario Balotelli"
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD