Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the caller script name

Tags:

python

file

I'm using Python 2.7.6 and I have two scripts:

outer.py

import sys
import os

print "Outer file launching..."
os.system('inner.py')

calling inner.py:

import sys
import os

print "[CALLER GOES HERE]"

I want the second script (inner.py) to print the name of the caller script (outer.py). I can't pass to inner.py a parameter with the name of the first script because I have tons of called/caller scripts and I can't refactor all the code.

Any idea?

like image 999
Gianx Avatar asked Jun 09 '14 06:06

Gianx


2 Answers

One idea is to use psutil.

#!env/bin/python
import psutil

me = psutil.Process()
parent = psutil.Process(me.ppid())
grandparent = psutil.Process(parent.ppid())
print grandparent.cmdline()

This is ofcourse dependant of how you start outer.py. This solution is os independant.

like image 168
jorgen Avatar answered Sep 19 '22 06:09

jorgen


On linux you can get the process id and then the caller name like so.

p1.py

import os
os.system('python p2.py')

p2.py

import os

pid = os.getppid()
cmd = open('/proc/%d/cmdline' % (pid,)).read()
caller = ' '.join(cmd.split(' ')[1:])
print caller

running python p1.py will yield p1.py I imagine you can do similar things in other OS as well.

like image 21
Fabricator Avatar answered Sep 22 '22 06:09

Fabricator