更改python 3中的硬编码值

时间:2018-11-20 07:46:09

标签: python-3.x hardcode

我想更改代码中的硬编码值。我希望代码根据其运行次数替换和更改硬编码值。始于:

x=1

下一次,我运行它之后,在代码本身中,我想在代码编辑器中看到:

x=2

它将自动更改代码的值,而无需人工输入,因此第三次运行:

x=3

这一切都是通过运行脚本来完成的,而无需人工干预。有简单的方法吗?

2 个答案:

答案 0 :(得分:2)

使用配置解析器将运行计数器存储在文件中

import configparser

config = configparser.ConfigParser()
config_fn = 'program.ini'

try:
    config.read(config_fn)
    run_counter = int(config.get('Main', 'run_counter'))
except configparser.NoSectionError:
    run_counter = 0
    config.add_section('Main')
    config.set('Main', 'run_counter', str(run_counter))
    with open(config_fn, 'w') as config_file:
        config.write(config_file)

run_counter += 1
print("Run counter {}".format(run_counter))
config.set('Main', 'run_counter', str(run_counter))
with open(config_fn, 'w') as config_file:
        config.write(config_file)

答案 1 :(得分:0)

您可以简单地写入定义明确的辅助文件:

# 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逐字记录。

 $ python3 test.py
 counter = 0
 $ python3 test.py
 counter = 1
 $ python3 test.py
 counter = 2
 $ cat my_counter
 3