How to get the caller script name

后端 未结 4 1221
天命终不由人
天命终不由人 2020-12-19 14:44

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\')
相关标签:
4条回答
  • 2020-12-19 14:50

    Another, a slightly shorter version for unix only

    import os
    parent = os.system('readlink -f /proc/%d/exe' % os.getppid())
    
    0 讨论(0)
  • 2020-12-19 15:03

    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
    
    0 讨论(0)
  • 2020-12-19 15:07

    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.

    0 讨论(0)
  • 2020-12-19 15:15

    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.

    0 讨论(0)
提交回复
热议问题