简体   繁体   English

运行代码之间的Python计数器

[英]Python counter between running code

I would like to limit the amount of times I print into a text file by using this code, every time I run the code below, a is defined as zero, how would I be able to make a counter which works by saving its value at the end of the code, and then restores its value when the code is next run? 我想通过使用此代码来限制我打印到文本文件中的次数,每次我运行下面的代码时,a都定义为零,我如何能够通过将其值保存在以下位置来使计数器工作代码的末尾,然后在下次运行代码时恢复其值?

a = 0
if a < 3:
    score = 5
    with open('tom.txt','a') as fo:
        fo.write('Tom: ')
        fo.write(str(score))
        fo.write("\n")
        a = a + 1

Anything would be appreciated thank you 任何事情将不胜感激谢谢

What about...: 关于什么...:

a = restore_state()
if a < 3:
    score = 5
    with open('tom.txt','a') as fo:
        fo.write('Tom: ')
        fo.write(str(score))
        fo.write("\n")
        a = a + 1
        save_state(a)

with eg 与例如

def save_state(a):
    with open('saveit', 'w') as f:
        f.write(str(a))

and

def restore_state():
    try:
        with open('saveit', 'r') as f:
            a = int(f.read())
    except IOError:
        a = 0
    return a

...? ...?

For a single integer, it's hard to be simpler than a plain text file. 对于单个整数,很难比纯文本文件更简单。 If you want to get more involved - more settings, different data types - you could use JSON ( import json ) or YAML ( import yaml ) or a config file ( import configparser ). 如果您想参与其中-更多设置,不同数据类型-您可以使用JSON( import json )或YAML( import yaml )或配置文件( import configparser )。

You need to define default settings (if the settings file does not exist, use the defaults), a function to load settings from a file, and a function to save settings to a file. 您需要定义默认设置(如果设置文件不存在,请使用默认设置),从文件加载设置的功能以及将设置保存到文件的功能。

import json

class Settings:
    def __init__(self, settings_file, default_values):
        self.settings_file  = settings_file
        self.default_values = default_values
        self.load()

    def load(self, load_file=None):
        if load_file is None:
            load_file = self.settings_file

        try:
            with open(load_file) as inf:
                self.values = json.load(inf)
        except FileNotFoundError:
            self.values = self.default_values

    def save(self, save_file=None):
        if save_file is None:
            save_file = self.settings_file

        with open(save_file, "w") as outf:
            json.dump(self.values, outf)

    def __getattr__(self, key):
        return self.values[str(key)]

    def __setattr__(self, key, value):
        if key in {"settings_file", "default_values", "values"}:
            return super(Settings, self).__setattr__(key, value)
        else:
            self.values[str(key)] = value
            return value

which you use like 你用像

state = Settings("my_settings.json", {"a": 0})

if state.a < 3:
    score = 5
    with open('tom.txt','a') as fo:
        fo.write('Tom: ')
        fo.write(str(score))
        fo.write("\n")
        state.a += 1

state.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM