Change hardcoded values in python 3

十年热恋 提交于 2020-05-12 08:15:31

问题


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?


回答1:


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

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



回答2:


Use config parser to store run counter in a file

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)


来源:https://stackoverflow.com/questions/53388362/change-hardcoded-values-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!