Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - How to redirect the errors to /dev/null?

Tags:

python

linux

I have this fun in my python script:

def start_pushdata_server(Logger):
    Logger.write_event("Starting pushdata Server..", "INFO")
    retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server 
start"))

we want to redirect the standard error from pushdata-server binary to /dev/null.

so we edit it like this:

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"))

But adding the 2>/dev/null in the python code isn't valid.

So how we can in the python code to send all errors from "pushdata-server start" to null?


2 Answers

This code added to a Python script running in Unix or Linux will redirect all stderr output to /dev/null

import os # if you have not already done this
fd = os.open('/dev/null',os.O_WRONLY)
os.dup2(fd,2)

If you want to do this for only part of your code:

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)

The part of your code to have stderr redirected goes here. Then to restore stderr back to where it was:

os.dup2(savefd,2)

If you want to do this for stdout, use 1 instead of 2 in the os.dup and os.dup2 calls (dup2 stays as dup2) and flush stdout before doing any group of os. calls. Use different names instead of fd and/or savefd if these are conflicts with your code.

like image 96
Skaperen Avatar answered Sep 14 '25 13:09

Skaperen


Avoiding the complexities of the run_shell(create_shell_command(...)) part which isn't well-defined anyway, try

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

This doesn't involve a shell at all; your command doesn't seem to require one.

like image 40
tripleee Avatar answered Sep 14 '25 14:09

tripleee