我想找点乐子,所以我决定看看在创建自重写脚本方面我能做些什么。我做了这个:
import os
import string
f = open('rewrite.py', 'r+')
text = f.read()
text = str(f.write("while True:" + text))
f.seek(0)
f.write(text)
f.close()
os.system("python rewrite.py")
但它有点混乱,因为它在插入 while 循环后不会缩进任何内容。文件本身也称为 rewrite.py。我知道这将是一个无限循环并创建一个大文件,但我想看看这是否可能。
编辑:运行此脚本后,文件内容现在如下所示:
Nonert os
import string
f = open('rewrite.py', 'r+')
text = f.read()
text = str(f.write("while True:" + text))
f.seek(0)
f.write(text)
f.close()
os.system("python rewrite.py")
while True:import os
import string
f = open('rewrite.py', 'r+')
text = f.read()
text = str(f.write("while True:" + text))
f.seek(0)
f.write(text)
f.close()
os.system("python rewrite.py")
python 代码写入 python 文件的最佳方法是什么?
关于这个问题的第二个答案真的做得很好。 我建议使用他制作的课程!
以下内容符合您正在尝试做的事情的精神。 请注意,我摆脱了while True:
,因为它可以防止您的程序第二次重新运行 - 它卡在无限循环中并且再也不会调用os.system()
。 在向此脚本添加任何其他内容之前,请仔细阅读三个if
子句。 运行风险自负:
import os
text = ''
f = open('rewrite.py', 'r+')
for line in f:
if line.startswith("import") or line.startswith("os.system"):
text += line
elif line == "n":
text += line
text += "for i in range(3):n"
else:
text += ' ' * 4 + line
f.seek(0)
f.write(text)
f.close()
os.system("python rewrite.py")
如果一切顺利,它最终应该停止并显示错误:
SystemError: too many statically nested blocks
只是为了我自己的目的发明了这段代码。 如果要通过将代码字符串写入模块来生成 python 函数,则需要匹配缩进,因此制表变得很重要:
def tabify_code(self, code:str):
lines = code.splitlines()
if len(lines) <= 1:
return code
tab_size = self.num_indent_spaces
orig_tab_size = 0
k = 0
for line in lines:
if line.strip():
spaces = 0
for c in line:
if c == ' ':
spaces += 1
else:
lines[k] = (spaces, line)
orig_tab_size = math.gcd(spaces, orig_tab_size)
break
k += 1
tabified = []
for (spaces, line) in lines:
if original_tab_size != 0:
tabs = int(spaces / orig_tab_size)
else:
tabs = 0
line = line.strip(' ')
line = f'{" " * tab_size * tabs}{line}'
tabified.append(line)
return "n".join(tabified)
它使用 GCD 来确定传入代码的给定选项卡大小。 这样我们就可以轻松计算需要多少个选项卡。 显然,GCD是合适的,并且确实适用于Python代码。