打印出 Python 脚本中的所有代码 [英] Print out all code in a Python script

查看:79
本文介绍了打印出 Python 脚本中的所有代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打印出 Python 脚本的内容?

How can I print out the contents of a Python script?

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

For example, if I have this (pointless example) script:

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

我可以添加什么行来恢复整个内容?

What line can I add to it, to get the entire contents back?

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

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

推荐答案

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

Programs that print out their source code are called quines. There are a few good examples here.

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

The easiest way is to read the script's source file:

print open(__file__).read()

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

If you can't read from the file, you'll need to wrap all your code in strings. You can then execute the strings and print them separately.

这篇关于打印出 Python 脚本中的所有代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆