打印Python脚本中的所有代码

打印Python脚本中的所有代码,python,reflection,Python,Reflection,如何打印Python脚本的内容 例如,如果我有这个(无意义的示例)脚本: 我可以添加哪一行来收回全部内容 my_var = 1 + 1 another_thing = "this is my string" # Magically print out all of the code in this file print ..... 打印源代码的程序称为quines。这里有几个很好的例子 最简单的方法是读取脚本的源文件: print open(__file__).read() 如果无法读取该

如何打印Python脚本的内容

例如,如果我有这个(无意义的示例)脚本:

我可以添加哪一行来收回全部内容

my_var = 1 + 1
another_thing = "this is my string"

# Magically print out all of the code in this file
print .....

打印源代码的程序称为quines。这里有几个很好的例子

最简单的方法是读取脚本的源文件:

print open(__file__).read()
如果无法读取该文件,则需要将所有代码包装为字符串。然后可以执行字符串并单独打印它们

print open(__file__).read()