Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stdout to dev/null not working with subprocess module in python3.6

Using Python 3.6.7 on Ubuntu 18.04.2 LTS

I am trying to invoke a shell script through python script, and expect the stdout to be null i.e. I do not want console output.

Snippet of the program

def command_execution(self, cmd, cwd=None):
    """ Execute the command cmd without console output
    and return the exitcode
    """
    FNULL = open(os.devnull, 'w') # Method1
    self.log.debug("Executing command " +  cmd)
    exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True,  stdout=subprocess.DEVNULL)
    # Method1 call exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True,  stdout=FNULL)

    (_,_) = exec_cmd.communicate()
    exitcode = exec_cmd.returncode
    self.log.debug("Executed command {0} with exitcode {1}".format(cmd, exitcode))
    return exitcode

As mentioned above, I tried both FNULL and subprocess.DEVNULL method. But, I still see the output on the console.

Am I missing anything here?

like image 730
malhar Avatar asked Jul 14 '26 13:07

malhar


1 Answers

Is it possible that your cmd is outputting to stderr, not stdout?

You can test by doing something like this:

exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True,  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
like image 97
ash Avatar answered Jul 17 '26 17:07

ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!