【问题标题】:Print out all code in a Python script打印出 Python 脚本中的所有代码
【发布时间】:2014-10-04 02:00:57
【问题描述】:

如何打印 Python 脚本的内容?

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

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

我可以添加哪一行来获取全部内容?

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

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

【问题讨论】:

    标签: python reflection


    【解决方案1】:

    打印出其源代码的程序称为quines。有几个很好的例子here

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

    print open(__file__).read()
    

    如果您无法从文件中读取,则需要将所有代码包装在字符串中。然后,您可以执行字符串并单独打印它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2013-03-21
      • 2012-03-07
      • 1970-01-01
      • 2012-01-22
      • 2013-01-04
      • 2021-06-26
      相关资源
      最近更新 更多