我该如何更改python脚本本身? [英] How can I make a python script change itself?
问题描述
如何更改python脚本本身?
How can I make a python script change itself?
要精简一下,我想要一个像这样的python脚本(run.py
)
To boil it down, I would like to have a python script (run.py
)like this
a = 0
b = 1
print a + b
# do something here such that the first line of this script reads a = 1
下次运行脚本时,它看起来像
Such that the next time the script is run it would look like
a = 1
b = 1
print a + b
# do something here such that the first line of this script reads a = 2
这有可能吗?该脚本可能使用外部资源.但是,只要运行一个run.py
文件,一切都应该工作.
Is this in any way possible? The script might use external resources; however, everything should work by just running the one run.py
-file.
可能还不够清楚,但是脚本应该更新自身,而不是其他文件.当然,一旦在脚本旁边允许一个简单的配置文件,此任务就变得微不足道了.
It may not have been clear enough, but the script should update itself, not any other file. Sure, once you allow for a simple configuration file next to the script, this task is trivial.
答案:
实际上比想象的要容易得多. @khelwood的建议效果很好,打开脚本并将其自己的内容写入其中完全没有问题. @Gerrat的解决方案也很好用.这就是我的想法:
It is actually much easier than thought. @khelwood 's suggestion works just fine, opening the script and writing it's own content to it is completely unproblematic. @Gerrat's solution also works nicely. This is how I'm having it:
# -*- coding: utf-8 -*-
a = 0
b = 1
print a + b
content = []
with open(__file__,"r") as f:
for line in f:
content.append(line)
with open(__file__,"w") as f:
content[1] = "a = {n}\n".format(n=b)
content[2] = "b = {n}\n".format(n=a+b)
for i in range(len(content)):
f.write(content[i])
推荐答案
例如(每次运行时更改a
的值):
For an example (changing the value of a
each time its run):
a = 0
b = 1
print a + b
with open(__file__, 'r') as f:
lines = f.read().split('\n')
val = int(lines[0].split(' = ')[-1])
new_line = 'a = {}'.format(val+1)
new_file = '\n'.join([new_line] + lines[1:])
with open(__file__, 'w') as f:
f.write('\n'.join([new_line] + lines[1:]))
这篇关于我该如何更改python脚本本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!