arshovon
arshovon

Reputation: 13651

Python subprocess is showing output in stderr

I created the following script to shutdown an Ubuntu machine after X minutes.

import subprocess

def execute_command(command):
    command = command.split()
    try:
        print(command)
        command_process = subprocess.run(command,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
        output = command_process.stdout.decode('utf-8')            
        output_message = "Command output: {}".format(output)
        error = command_process.stderr.decode('utf-8')            
        error_message = "Command error: {}".format(error)
        print(output_message)
        print(error_message)
    except Exception as error:
        command_error = str(error)
        print("Error: "+command_error)

command = "shutdown -h 50"
execute_command(command)

Output:

['shutdown', '-h', '50']
Command output: 
Command error: Shutdown scheduled for Sat 2018-04-21 19:37:25 +06, use 'shutdown -c' to cancel.

My questions:

  1. Why stdout is empty?
  2. Why the message is shown in stderr? Is there any error in my script?

Upvotes: 1

Views: 63

Answers (1)

ash
ash

Reputation: 5539

Your code seems correct; the shutdown command appears to send its output to stderr:

$ shutdown +9 >/dev/null
Shutdown scheduled for Sat 2018-04-21 15:38:00 BST, use 'shutdown -c' to cancel.

whereas shutdown +9 2>/dev/null produces no output.

Explanation:

  • > redirects stdout to a file
  • 2> redirects stderr to a file
  • /dev/null is a special file that discards all things written to it

Reference: TLDP

Upvotes: 1

Related Questions