4

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?

  • no need to add `2>/dev/null`. Python will capture `stderr` if you specified the respective option. Learn and use `subprocess` module – RomanPerekhrest Nov 17 '17 at 09:43
  • the problem is that output from command (errors) send to standard output "to the screen" so we want to avoid that –  Nov 17 '17 at 09:46
  • 1
    Where and how is `run_shell` defined? Why do you want to run the server inside a shell? – tripleee Nov 27 '17 at 10:46

2 Answers2

4

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.

Skaperen
  • 453
  • 4
  • 13
  • 1
    can you advice me please based on my code how to re-edit it based on your solution ? –  Nov 17 '17 at 10:02
  • @yael i do not know about your `run_shell()` and `create_shell_command()` functions so i do not know if i can work correctly with your code. did you write those functions? there may also be alternate, and perhaps better, ways to do this in those functions. – Skaperen Nov 18 '17 at 03:54
1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Basically stolen (with updates for recent Python 3.x) from here: https://stackoverflow.com/questions/8529390/is-there-a-quiet-version-of-subprocess-call – tripleee Nov 27 '17 at 11:02