2013-05-07 54 views
-1

假设你有像这样有没有办法在python文件中执行时获取python文件的源代码?

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

你怎么能得到整个文件的源Python文件,包括与高管的意见吗?

+0

你想要当前模块/脚本的来源?为什么?是否与这个问题有关的'exec'?如果是这样,怎么样? (你为什么要这样做呢?) – abarnert 2013-05-07 20:36:47

+0

听起来像有人在网页脚本中发现了一个洞... – MattDMo 2013-05-07 20:59:56

回答

1

如果你不完全绑定到使用EXEC,这很简单:

print open(__file__).read() 
+0

虽然它可能被认为是作弊,但我认为这是一个很好的例子。 http://en.wikipedia.org/wiki/Quine_(computing)也回答这个问题! – 2013-05-07 20:33:48

+0

除了这不可能读取压缩/冻结/等。源文件...并可以读取二进制文件,就好像它是文本一样。 – abarnert 2013-05-07 20:35:50

2

这也正是inspect模块是有什么。特别参见Retrieving source code部分。

如果你想获得当前正在运行的模块的源:

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

不知道你打算怎么用这个,但我一直在使用这个方法可以减少维护所需的工作我的命令行脚本。我一直用开放(_ 文件 _,“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运行程序选项。

+0

为什么? 'inspect.getdoc',会给你一个模块(或任何其他对象)的文档字符串。它将处理双引号的文档字符串,可能还有其他许多代码不会的东西,它通过'cleandoc'运行。 – abarnert 2013-05-07 20:38:18

+0

另外...是不是这只是一个非常复杂的方式来编写'split'? – abarnert 2013-05-07 20:41:33

+0

这是我第一次听说检查模块。我同意这是一个更好的解决方案。 – tweirick 2013-05-07 20:45:04