th0mash
th0mash

Reputation: 195

subprocess choose between stdout and os.devnull

For a project I would like to write a code that I want to reuse in various part of my project. I need to execute a command and want to be able to choose between printing in the console or muting the command. I have came up with that, but I am not sure if it is okay and if the "with" works correctly this way:

import os
import sys
import subprocess

def run_subprocess(cmd, display_output : bool=False):
    if display_output:
        stdout = sys.stdout
    else:
        stdout = open(os.devnull, "w")
        
    with stdout as s:
        exit_code = subprocess.call([cmd], shell=True, stdout=s)
    return exit_code

Is it ok to do this way ? Should I change something ? Thanks!

Upvotes: 1

Views: 559

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 52079

Use the sentinel subprocess.DEVNULL for /dev/null or the default None for stdout instead:

import subprocess

def run_subprocess(cmd, display_output: bool = False):
    stdout = None if display_output else subprocess.DEVNULL
    return subprocess.call([cmd], shell=True, stdout=stdout)

Using these makes subprocess handle both targets properly and in a system-independent way.

Upvotes: 1

th0mash
th0mash

Reputation: 195

I found something way cleaner that I am using, still not sure if it is 'good practice' but it seems to be quite okay for my application

import os
import subprocess

def run_subprocess(cmd, display_output: bool = False):
    with open(os.devnull, "w") as s:
        args = {'stdout': s} if display_output else {}
        exit_code = subprocess.call([cmd], shell=True, **args)
    return exit_code

Upvotes: 0

Related Questions