Assuming you have a python file like so
#python
#comment
x = raw_input()
exec(x)
How could you get the source of the entire file, including the comments with exec?
Assuming you have a python file like so
#python
#comment
x = raw_input()
exec(x)
How could you get the source of the entire file, including the comments with exec?
This is exactly what the inspect
module is there for. See the Retrieving source code section in particular.
If you're trying to get the source of the currently-running module:
thismodule = sys.modules[__name__]
inspect.getsource(thismodule)
If you're not totally bound to using exec, this is simple:
print open(__file__).read()
Not sure what you are planning to use this for, but I have been using this to reduce work required to maintain my command line scripts. I always used 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())
This way your comments at the top of the program will be output when your run the program from command line with the --help option.