9

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?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Gianx
  • 233
  • 3
  • 11
  • I don't think is possible when you use `os.system`. You essentially go through os and invoke a new python session. You could set up some environment variable in `outer.py`, when calling `system` with it's name, and check for its presence in `inner.py`. I don't think there are any other workarounds. – luk32 Jun 09 '14 at 06:29
  • If you're planning to make `inner.py` do different things depending on who calls it, that's going to be a maintenance nightmare. – user2357112 Jun 09 '14 at 06:30

4 Answers4

9

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.

jorgen
  • 688
  • 6
  • 16
5

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.

Fabricator
  • 12,722
  • 2
  • 27
  • 40
1

Another, a slightly shorter version for unix only

import os
parent = os.system('readlink -f /proc/%d/exe' % os.getppid())
Alex
  • 93
  • 1
  • 5
-1

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
Basic Block
  • 729
  • 9
  • 17