Gianx
Gianx

Reputation: 243

How to get the caller script name

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?

Upvotes: 10

Views: 9593

Answers (4)

Alex
Alex

Reputation: 103

Another, a slightly shorter version for unix only

import os
parent = os.system('readlink -f /proc/%d/exe' % os.getppid())

Upvotes: 1

Basic Block
Basic Block

Reputation: 781

If applicable to your situation you could also simply pass an argument that lets inner.py differentiate:

import sys
import os

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

innter.py

import sys
import os

try:
    if sys.argv[0] == 'launcher':
        print 'outer.py called us'
except:
    pass

Upvotes: -1

jorgen
jorgen

Reputation: 737

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.

Upvotes: 9

Fabricator
Fabricator

Reputation: 12772

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.

Upvotes: 5

Related Questions