在 python 3 中更改硬编码值 [英] Change hardcoded values in python 3
问题描述
我想更改代码中的硬编码值.我希望代码根据运行次数替换和更改硬编码值.开头:
I would like to change hardcoded values in my code. I would like the code to replace and change hardcoded values based on the number of times it runs. Beginning with:
x=1
下一次,在我运行它之后,在代码本身中,我想在代码编辑器中看到:
The next time, after I run it, in the code itself, I would like to see in the code editor:
x=2
它会在没有人工输入的情况下自动改变代码的值,所以第三次运行:
It will automatically change the values of the code without human input, so the third time its run:
x=3
这一切都是通过脚本运行完成的,没有任何人为交互.有没有简单的方法?
And this is all done just by the script running, no human interaction whatsoever. Is there an easy way?
推荐答案
你可以简单地写入一个定义良好的辅助文件:
You can simply write to a well-defined auxiliary file:
# define storage file path based on script path (__file__)
import os
counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
# start of script - read or initialise counter
try:
with open(counter_path, 'r') as count_in:
counter = int(count_in.read())
except FileNotFoundError:
counter = 0
print('counter =', counter)
# end of script - write new counter
with open(counter_path, 'w') as count_out:
count_out.write(str(counter + 1))
这将在您的脚本旁边存储一个辅助文件,其中包含逐字逐字的 counter
.
This will store an auxiliary file next to your script, which contains the counter
verbatim.
$ python3 test.py
counter = 0
$ python3 test.py
counter = 1
$ python3 test.py
counter = 2
$ cat my_counter
3
这篇关于在 python 3 中更改硬编码值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!