Python script to enter next number in sequence on every run.

I am trying to write a script that will have a counter that will start 001 and increment by one each time the script is run.

I'll just help, help, started this, what can I do to set it up so that he knows where it starts every time? Is there a way that I can create it in a script to do this?

My bad ideas on how to do this so far: - Have the number (001) exported to a text file and the script change that number at the end of each script (001 +1).

  • This number will also appear in the spreadsheet, so read the script value from the spreadsheet and add the value to that value.

I feel like there should be an easier way and I would prefer it to be self contained within the script. Can anyone help me in the right direction?

Thanks for your input.

+3


source to share


3 answers


Here's a quick example of persisting state using INI files and JSON files. Both attempts to read the configuration file, update or initialize the counter, save the new counter back to the config, and then return the counter.



#!/usr/bin/env python3

import configparser
import json
from contextlib import suppress


def get_updated_ini_counter():
    filename = 'config.ini'
    section = 'general'
    option = 'counter'
    starting_count = 100

    config = configparser.ConfigParser()
    config.read(filename)
    counter = 1 + int(config.get(section, option, fallback=starting_count - 1))
    if section not in config:
        config.add_section(section)
    config.set(section, option, str(counter))
    with open('config.ini', 'w') as f:
        config.write(f)
    return counter


def get_updated_json_counter():
    filename = 'config.json'
    option = 'counter'
    starting_count = 100
    config = {}

    with suppress(FileNotFoundError):
        with open(filename) as f:
            config = json.load(f)
    config[option] = 1 + config.get(option, starting_count - 1)
    with open(filename, 'w') as f:
        json.dump(config, f, indent=4)
    return config[option]


if __name__ == '__main__':
    print('ini counter  = {}'.format(get_updated_ini_counter()))
    print('json counter = {}'.format(get_updated_json_counter()))

      

+2


source


If you want some kind of state, then your options are limited:



  • save state to file as you suggest in your question (text file or spreadsheet but spreadsheet is more difficult)
  • change your concept so that instead of "run the script" multiple times, the script always works, but you give it some kind of signal (keyboard input, GUI with a button, etc.) to tell it to increment the counter
  • split the script into two halves, the server script and the client. the server will listen for connections from the client and keep track of the current counter, then the client will connect and indicate to the server to increase the account, if necessary, it can also send the previous or new account back to the client for some kind of withdrawal. this would prevent a lot of disk writes, but the count will be lost if the server process is closed.
+3


source


This sounds like a broad question. But say your script is hello.py

and it just prints "hello world"

, and for the simple case where you use this script on your desktop / laptop, just include a few lines to keep track of when you last ran the script.

import datetime

def hello():
    print "hello, world"

if __name__ == "__main__":

    now = datetime.datetime.now()
    ## create log
    with open("logs.txt", "a") as log:
        log.write(str(now) + "\n") ## write out to log 

    ## run hello
    hello()

      

Of:

>python hello.py
hello, world
>python hello.py
hello, world
>python hello.py
hello, world
>python hello.py
hello, world
>python hello.py
hello, world
>cat logs.txt
2017-04-21 10:38:46.629779
2017-04-21 10:38:47.229658
2017-04-21 10:38:47.664318
2017-04-21 10:38:47.957451
2017-04-21 10:38:48.279116

      

If you need to know the number of times that you have run the script on a specific day / hour, you can just export that to Excel or something to show you the distribution of usage over time.

Update using atexit:

Here is the above example using atexit

The atexit module defines one function to register cleanup functions. Registered functions are automatically executed when the normal interpreter exits.

import atexit
import datetime

def hello():
    print "hello, world"

def saveDateTime():
    now = datetime.datetime.now()
    ## create log
    with open("logs.txt", "a") as log:
        log.write(str(now) + "\n")

def goodbye():
    try:
        _dates = open("logs.txt").read()
        _count = len(_dates)
    except IOError:
        _count = 0
    print 'Goodbye, this script has been run %d times.' % (_count)

if __name__ == "__main__":
    hello() ## run hello
    atexit.register(saveDateTime) ## then log when you used this
    atexit.register(goodbye) ## then log when you used this

      

+1


source







All Articles