2013-04-30 7 views
5

मुझे किसी फ़ंक्शन को परिभाषित करना चाहिए, where, जो बता सकता है कि इसे कहां निष्पादित किया गया था, जिसमें कोई तर्क पारित नहीं हुआ था? सभी फाइलों में ~/ऐप्स/निर्धारित करें कि कोई फ़ंक्शन निष्पादित किया गया था?

a.py:

def where(): 
    return 'the file name where the function was executed' 

b.py:

from a import where 
if __name__ == '__main__': 
    print where() # I want where() to return '~/app/b.py' like __file__ in b.py 

c.py:

from a import where 
if __name__ == '__main__': 
    print where() # I want where() to return '~/app/c.py' like __file__ in c.py 
+4

जैसा कि आप ध्यान देते हैं, आपके पास पहले से ही वह जानकारी है जिसे आप '__file__' के रूप में चाहते हैं। इसे वापस करने के लिए आपको एक फ़ंक्शन लिखने की आवश्यकता क्यों है? – kindall

+0

यहां एक नज़र डालें: http://docs.python.org/2/library/inspect.html – StoryTeller

+0

@kindall मैं चाहता हूं कि() पता है कि इसे कहां निष्पादित किया गया है, और इसे अपने फ़ंक्शन बॉडी में एक विविध के रूप में उपयोग करें। – walknotes

उत्तर

11

आप देखने की जरूरत है inspect.stack() का उपयोग करके कॉल स्टैक:

from inspect import stack 

def where(): 
    caller_frame = stack()[1] 
    return caller_frame[0].f_globals.get('__file__', None) 

या यहाँ तक कि:

def where(): 
    caller_frame = stack()[1] 
    return caller_frame[1] 
1
import sys 

if __name__ == '__main__': 
    print sys.argv[0] 

sys.argv [0] हमेशा की तरह, नाम/फ़ाइल चल रहा है का मार्ग है भी नहीं तर्क

3

में पारित के साथ आप उपयोग कर सकते हैं traceback.extract_stack:

import traceback 
def where(): 
    return traceback.extract_stack()[-2][0] 
0

इस के आधार पर ...

print where() # I want where() to return '~/app/b.py' like __file__ in b.py 

... यह आपके द्वारा निष्पादित की जा रही स्क्रिप्ट का योग्य पथ है जैसा लगता है।

जो मामले में, कोशिश ...

import sys 
import os 

if __name__ == '__main__': 
    print os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))) 

realpath() का उपयोग करते हुए इस मामले में जहां आप एक प्रतीकात्मक कड़ी से स्क्रिप्ट चला रहे हैं के साथ सामना करना चाहिए।

संबंधित मुद्दे