【问题标题】:Change hardcoded values in python 3在 python 3 中更改硬编码值
【发布时间】:2025-12-25 14:00:06
【问题描述】:

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

x=1

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

x=2

它会在没有人工输入的情况下自动更改代码的值,所以第三次运行:

x=3

这一切都是通过脚本运行完成的,没有任何人为交互。有什么简单的方法吗?

【问题讨论】:

  • 一种选择是在脚本末尾以写入模式打开 .py 文件,找到要修改的行并替换该值。
  • 当然是可能的 - 大多数情况都是如此。可取的?并不真地。如果此值需要在运行中保持不变,那么请考虑将其存储在一个文件中,您每次都可以从脚本中加载该文件。
  • 当然可以,但是有没有简单的方法?我希望这些值是动态的,就像 1 变成 2。让我重新表述一下

标签: python-3.x hardcode


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

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

    # 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
    

    【讨论】: