-1

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

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

您如何获得整个文件的来源,包括 exec 的注释?

4

3 回答 3

2

这正是该inspect模块的用途。具体参见检索源代码部分。

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

thismodule = sys.modules[__name__]
inspect.getsource(thismodule)
于 2013-05-07T20:34:04.613 回答
1

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

print open(__file__).read()
于 2013-05-07T20:14:27.847 回答
0

不确定您打算将其用于什么,但我一直在使用它来减少维护命令行脚本所需的工作。我一直用 open( _file _ , '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 选项从命令行运行程序时,将输出程序顶部的注释。

于 2013-05-07T20:36:40.597 回答