Linux python-如何将错误重定向到/dev/null?

Linux python-如何将错误重定向到/dev/null?,linux,python,Linux,Python,在我的python脚本中有这样的乐趣: def start_pushdata_server(Logger): Logger.write_event("Starting pushdata Server..", "INFO") retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server start")) 我们希望将标准错误从pushdata服务器二进制文件重定向到/dev/null 所以我们像

在我的python脚本中有这样的乐趣:

def start_pushdata_server(Logger):
    Logger.write_event("Starting pushdata Server..", "INFO")
    retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server 
start"))
我们希望将标准错误从pushdata服务器二进制文件重定向到/dev/null

所以我们像这样编辑它:

def start_pushdata_server(Logger):
    Logger.write_event("Starting pushdata Server..", "INFO")
    retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server 
start 2>/dev/null"))
但是在python代码中添加
2>/dev/null
是无效的

那么我们如何才能在python代码中从“pushdata服务器”发送所有错误呢
start“to null?

此代码添加到在Unix或Linux中运行的Python脚本中,将所有stderr输出重定向到/dev/null

import os # if you have not already done this
fd = os.open('/dev/null',os.O_WRONLY)
os.dup2(fd,2)
如果只想对部分代码执行此操作:

import os # if you have not already done this
fd = os.open('/dev/null',os.O_WRONLY)
savefd = os.dup(2)
os.dup2(fd,2)
将stderr重定向到此处的代码部分。然后将stderr恢复到原来的位置:

os.dup2(savefd,2)

如果要对stdout执行此操作,请在
os.dup
os.dup2
调用中使用1而不是2(
dup2
保持为
dup2
),并在执行任何一组
os.
调用之前刷新stdout。如果这些名称与您的代码冲突,请使用不同的名称,而不是
fd
和/或
savefd

避免
运行shell(create\u shell\u命令(…)
部分的复杂性,这部分无论如何定义都不好,请尝试

import subprocess
subprocess.run(['pushdata-server', 'start'], stderr=subprocess.DEVNULL)

这根本不涉及外壳;您的命令似乎不需要它。

无需添加
2>/dev/null
。如果指定了相应的选项,Python将捕获stderr。了解并使用
子流程
模块问题在于,命令输出(错误)会发送到标准输出“到屏幕”,因此我们希望避免在哪里以及如何定义
运行shell
?你为什么要在shell中运行服务器?你能根据我的代码建议我如何根据你的解决方案重新编辑它吗?@yael我不知道你的
run\u shell()
create\u shell\u command()
函数,所以我不知道我是否能正确使用你的代码。你写了那些函数吗?在这些函数中也可能有替代方法,也许更好。基本上是从这里偷来的(对最近的Python 3.x进行了更新):