Linux – How to determine the PID of the python program if there is more then one python program running

bashlinuxpidpython

I have two python programs running on my system, say they are called program x and program y.

I want to get the pid of program y, but not x for my bash script. When using pgrep python, I get the pid of both of them and don't know which is which.

Any ideas how I tell the difference between the two in a bash script?

Best Answer

  • You can match against the argument list by using the -f switch to pgrep (try man pgrep to read more).

    pgrep -f x
    

    should yield only program x and

    pgrep -f y
    

    respectively only program y.

    As an alternative, if x and y are not unique enough and end in too many rows, you could use ps and grep to have more options

    ps ax | grep 'python x' | grep -v grep | awk '{print $1}'
    

    This will

    • list all relevant processes
    • grep for the ones with python x in it. In here you might need to add a path specifier like python ./path/to/x
    • remove the grep command itself from the list of matched processes
    • print only the first column, which is the pid.