Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在自重写脚本中以编程方式缩进Python代码?_Python - Fatal编程技术网

在自重写脚本中以编程方式缩进Python代码?

在自重写脚本中以编程方式缩进Python代码?,python,Python,我想找点乐子,所以我决定看看在创建自重写脚本方面我能做些什么。我做了这个: 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循环后没有缩进任何内容。文件本身

我想找点乐子,所以我决定看看在创建自重写脚本方面我能做些什么。我做了这个:

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")

我希望下面的内容符合你所要做的事情的精神。注意:我去掉了
而为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


关于这个问题的第二个答案做得很好。我建议使用他制作的课程

f.write
返回一个整数-此代码的作用与您认为的不同。如何迭代并在每行之前添加
(4个空格)呢?抱歉,@nneonno已修复。如果您想要缩进,为什么不添加它?不确定您的问题到底是什么,只有您知道文件中的内容,缩进由您来添加
f.write(“\n”+text+”\n而True:\n\tpass”)
忘记所有的剩余栏打开、关闭和读取,您可能需要执行
f.seek(0);f、 在编写之前截断()
,并准备好终止脚本