I think I've found a pretty safe way to do find the proper python process PID for a specific file only. The idea is to find all the python processes, then all "test.py" processes and intersect the results to find the correct PID.
I use the subprocess module in a python script (you can interpolate for .sh script):
import subprocess as subp
#Get a list of all processes with a certain name
def get_pid(name):
return list(map(int,subp.check_output(["pidof", "-c", name]).split()))
#Get a list of all pids for python3 processes
python_pids = get_pid('python3')
#Get a list of all pids for processes with "main.py" argument
main_py_pids = list(map(int,subp.check_output(["pgrep", "-f", "main.py"]).split()))
python_main_py_pid = set(python_pids).intersection(main_py_pids)
print(python_pids)
print(main_py_pids)
print(python_main_py_pid)
Result with 3 running python processes (including the one from this script) and one "sudo nano main.py" process:
Python pids: [3032, 2329, 1698]
main.py pids: [1698, 3031]
Interesection: {1698}