输出源代码的Python代码

之前用C写过打印程序本身的程序,现在用Python写一遍

1
2
3
import sys
with open(sys.argv[0]) as f:
print(f.read(), end ='')

但是利用传入参数读文件属实耍赖,所以在写一个不用读文件的版本:

1
2
3
4
5
6
7
8
9
10
11
12
a = list(range(6))
a[0] = 'a = list(range(6))'
a[1] = 'print(a[0])'
a[2] = 'for i in range(6):'
a[3] = ' print("a["+str(i)+"] = "+chr(39)+a[i]+chr(39))'
a[4] = 'for i in range(1,5): print(a[i])'
a[5] = 'print(a[5], end = "")'
print(a[0])
for i in range(6):
print("a["+str(i)+"] = "+chr(39)+a[i]+chr(39))
for i in range(1,5): print(a[i])
print(a[5], end = "")

最后一行是因为Python默认以print回车结尾
我无法用tab缩进,只能用空格缩进,这是唯一不完美的地方

欧尼酱,人家想喝可乐!