如何使用os.popen抑制控制台输出?- Python
在使用 popen
来执行 Unix 命令时,我会在控制台看到一些输出。
我知道 subprocess.popen
有一些功能可以抑制输出。抑制 subprocess.Popen 的输出
那么 os.popen
也有相同的抑制功能吗?
请注意,我的 Unix 命令中有管道,而我无法让 subprocess.Popen
正常工作。我的命令是这样的:
$ echo "es ist also grotesk , wenn herr jospin die europäische richtlinie und die britische datumsgestützte ausfuhrregelung gröblichst mißachtet und durch seine eigenen bedingungen zu ersetzen trachtet ." | treetagger/cmd/tree-tagger-german-utf8
3 个回答
0
可以这样做:
result = subprocess.Popen(['command'],
stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0]
更多信息可以在文档中找到。
1
直接使用 subprocess.check_output
就可以了。它会把输出结果以字符串的形式保存给你,而且还会自动检查错误(如果命令执行失败,它会抛出一个错误)。
2
不要使用管道,也不要用 os.popen
:
import subprocess
text = "es ist also ..."
tt = subprocess.Popen('treetagger/cmd/tree-tagger-german-utf8',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
tagged, stderr = tt.communicate(txt)
在我以前担任 Text+Berg 语料库 的处理管道开发者时,我为 TreeTagger 写了一个封装类,绕过了那些质量不太好的封装脚本。不幸的是,这段代码是专有的。