Bootstrap FreeKB - Python (Scripting) - Caller script
Python (Scripting) - Caller script

Updated:   |  Python (Scripting) articles

Let's say you have a Python script that will be called by other processes. If your Python script is running on a Linux system, here is how you should be able to determine the caller process using os and subprocess. This basically used the ps command to get the process ID of the caller script and then returns field 8, which should be the calling program.

#!/usr/bin/python3
import os
import subprocess

pid = os.getppid()

stdout = subprocess.Popen(f"ps -ef | grep {pid} | grep -v grep", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

if stdout != '':
  for line in stdout.decode('utf-8').strip().splitlines():
    fields = line.split()
    if int(fields[1]) == pid:
      try:
        fields[8]
      except IndexError:
        print(f"This script failed to determine the caller script")
        pass
      else:
        print(f"This script was called by {fields[8]}")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f7f6a2 in the box below so that we can be sure you are a human.