2

I have a very simple piece of code

import subprocess
print(subprocess.check_output(["pidof","ffmpeg"]))

that should print the PID(s) of processes named ffmpeg (see here). However, I always get the following error:

subprocess.CalledProcessError: Command '['pidof', 'ffmpeg']' returned non-zero exit status 1

for python2 and python3. What am I doing wrong?

Alex
  • 41,580
  • 88
  • 260
  • 469

2 Answers2

2

From man pidof:

EXIT STATUS
       0      At least one program was found with the requested name.

       1      No program was found with the requested name.

You just don't have any process named ffmpeg.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
  • But when I run the same command on bash, I do not get an error message. But an exit of 1 though – Alex Apr 26 '19 at 09:09
  • `check_output` is designed to raise `CalledProcessError` if process exited with non-zero code: https://docs.python.org/3.7/library/subprocess.html#subprocess.check_output – sanyassh Apr 26 '19 at 09:17
1

you can use try except to avoid the execution from blocking

use this

import subprocess

try:

    print(subprocess.check_output(["pidof","ffmpeg"]))
except subprocess.CalledProcessError:
    print("no process named ffmpeg")

you are getting error because if pidof ffmpeg gives no output and using print(subprocess.check_output(["pidof","ffmpeg"])) we are expecting output from that command.

also you can use

print(subprocess.getoutput("pidof ffmpeg"))

which will give no error even if output from that command is none

if you check the library method check_output you can find this

def check_output(*popenargs, timeout=None, **kwargs):
    r"""Run command with arguments and return its output.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.... """
Nihal
  • 5,262
  • 7
  • 23
  • 41