有没有办法在python文件中执行时获取python文件的源?

时间:2013-05-07 20:04:25

标签: python

假设你有一个像这样的python文件

#python
#comment
x = raw_input()
exec(x)

你怎么能得到整个文件的来源,包括exec的评论?

3 个答案:

答案 0 :(得分:2)

这正是inspect模块的用途。请参阅Retrieving source code部分。

如果您正在尝试获取当前正在运行的模块的来源:

thismodule = sys.modules[__name__]
inspect.getsource(thismodule)

答案 1 :(得分:1)

如果您不完全使用exec,这很简单:

print open(__file__).read()

答案 2 :(得分:0)

不确定您打算如何使用它,但我一直在使用它来减少维护命令行脚本所需的工作。我一直用open( _ 文件 _ ,'r')

'''
Head comments ...
'''
.
.
. 
def getheadcomments():
    """
    This function will make a string from the text between the first and 
    second ''' encountered. Its purpose is to make maintenance of the comments
    easier by only requiring one change for the main comments. 
    """
    desc_list = []
    start_and_break = "'''"
    read_line_bool = False
    #Get self name and read self line by line. 
    for line in open(__file__,'r'):
        if read_line_bool:
            if not start_and_break in line:
                desc_list.append(line)
            else:
                break    
        if (start_and_break in line) and read_line_bool == False:
            read_line_bool = True
    return ''.join(desc_list)
.
.
.
parser = argparse.ArgumentParser(description=getheadcomments())  

这样,当您使用--help选项从命令行运行程序时,将输出程序顶部的注释。

相关问题