linux 查找和列出重复python示例的Bash脚本

lvmkulzt  于 2023-02-15  发布在  Linux
关注(0)|答案(1)|浏览(121)

我正在尝试编写一个bash脚本来查找在Pi上运行的python脚本的重复示例。下面的脚本正在工作,并识别同一脚本的重复示例的Python(不是Python3)。我按预期获得了PID,但无法获得脚本的完整路径和名称。
我已经创建了一个脚本的两个示例:

bms       9189  0.0  0.1  10592  7248 ?        S    09:11   0:00 python -u /home/bms/Dev/APItest/APItest.py
bms       9192  0.0  0.1  10592  7188 ?        S    09:12   0:00 python -u /home/bms/Dev/APItest/APItest.py

下面是我从bash脚本中得到的输出:

Found 2 instances of -u:
PID: 9189, Script path: -u
PID: 9192, Script path: -u
Finished checking for duplicate Python scripts.

我希望得到如下输出:

PID: 9189, Script path: home/bms/Dev/APItest/APItest.py
PID: 9192, Script path: home/bms/Dev/APItest/APItest.py

这是我正在使用的脚本:

#!/bin/bash

# Get a list of all running Python processes
PYTHON_PROCESSES=$(ps aux | grep '[p]ython' | grep -v 'python3' | awk '{print $2}')

# Loop through the Python processes and count how many times each script is running
declare -A SCRIPT_COUNTS
declare -A SCRIPT_PIDS
for PID in $PYTHON_PROCESSES; do
    CMD=$(ps -p $PID -o comm=)
    if [ "$CMD" == "python" ]; then
        SCRIPT_ARGS=$(ps -p $PID -o args=)
        SCRIPT_PATH=$(echo "$SCRIPT_ARGS" | awk '{print $2}')
        SCRIPT_NAME=${SCRIPT_PATH##*/}
        if [ -z "${SCRIPT_COUNTS[$SCRIPT_NAME]}" ]; then
            SCRIPT_COUNTS[$SCRIPT_NAME]=0
        fi
        ((SCRIPT_COUNTS[$SCRIPT_NAME]++))
        if [ -z "${SCRIPT_PIDS[$SCRIPT_NAME]}" ]; then
            SCRIPT_PIDS[$SCRIPT_NAME]=""
        fi
        SCRIPT_PIDS[$SCRIPT_NAME]="${SCRIPT_PIDS[$SCRIPT_NAME]}$PID:$SCRIPT_PATH "
    fi
done

# Loop through the script counts and print the names of any scripts that have     duplicates
for SCRIPT_NAME in "${!SCRIPT_COUNTS[@]}"; do
    COUNT=${SCRIPT_COUNTS[$SCRIPT_NAME]}
    if [ $COUNT -gt 1 ]; then
        echo "Found $COUNT instances of $SCRIPT_NAME:"
        for INSTANCE in ${SCRIPT_PIDS[$SCRIPT_NAME]}; do
            PID=${INSTANCE%%:*}
            SCRIPT_PATH=${INSTANCE#*:}
            echo "PID: $PID, Script path: $SCRIPT_PATH"
        done
       fi
    done

echo "Finished checking for duplicate Python scripts."

如果代码中有任何不对齐的地方,请道歉。不得不手动调整以适应画布。我的问题是:我应该改变什么来获得想要的输出(PID加上完整的路径和副本的名称)。

dy2hfwbg

dy2hfwbg1#

为什么不是这个简单的awk

$ <INPUT> | awk '{print "PID: " $2 ", Script path: " $NF}' file
PID: 9189, Script path: /home/bms/Dev/APItest/APItest.py
PID: 9192, Script path: /home/bms/Dev/APItest/APItest.py

相关问题