79321163

Date: 2025-01-01 04:46:01
Score: 0.5
Natty:
Report link

welcome to programming, to Python, and StackOverflow.

Variables created during the execution of a script cease to exist when that script's execution ends. You cannot, therefore, record the number of times a script has run in a variable.

If you want information generated by or during the execution of a script to persist, you must save that information to a file in a process called serialisation.

In your case, you could write a snippet of code that executes every time some script (or even some function in that script - as in my example below) runs or is invoked, that opens a file, reads its contents, and then modifies those contents to reflect the fact that the script/function has been run/invoked.

I've set out a (somewhat elaborate) example below of how you might set something like this up. All this boilerplate code might seem excessive to merely count the number of times something has run - and it IS - but this approach could avail you if you wanted to capture more sophisticated diagnostic metrics about your script's operation (for instance, the values of some variables that were created during your script's execution).

import json
from pathlib import Path
from typing import Optional


def initialise_execution_count(path_to_file: Path) -> None:
    """
    If an execution count (json) file exists at the provided target
    path, opens the file and sets its "count" to 0. If the file doesn't
    exist, creates the file and sets count to 0.

    """

    with open(path_to_file, mode="w") as f:
        data: dict = dict(count=0)
        json.dump(data, f)


def read_execution_count(path_to_file: Path) -> int:
    """
    Reads the json file at the target path provided and returns the
    "count" value. If no file exists at the target path, initialises
    execution count at that target path and returns 0.

    """
    try:
        with open(path_to_file, mode="r") as f:
            data: dict[str, int] = json.load(f)
        return data["count"]
    except FileNotFoundError:
        initialise_execution_count(path_to_file=path_to_file)
        return 0


def increment_execution_count(path_to_file: Path) -> None:
    """
    Reads the currently recorded execution count at the target path, and
    updates the file at the target path to register the next higher
    count.

    """
    current_count = read_execution_count(path_to_file)
    new_count = current_count + 1
    with open(path_to_file, mode="w") as f:
        data = dict(count=new_count)
        json.dump(data, f)


def some_func(execution_count_file: Optional[Path] = None) -> None:
    """
    Some function that executes some logic and optionally takes an
    target path to an execution count file. If an execution count file
    is provided, calls increment_execution_count on the target path
    every time this function is run.

    This logic could be placed within a script so that every time the
    script is run, the execution count is incremented by one.

    """
    print("Running some func")
    if execution_count_file is not None:
        increment_execution_count(execution_count_file)


def main():
    """
    The main function that runs when this script is run. 
    """
    # Define the path to the file where I want the execution count to be 
    # recorded. 
    execution_count_filename = Path("some_func_execution_count.json")

    # Initialise the execution count. 
    initialise_execution_count(execution_count_filename)
    
    # Call "some_func" 10 times. This is analogous to running some 
    # script 10 times. 
    for _ in range(10):
        some_func(execution_count_file=execution_count_filename)
        # Print the current execution count to the screen. 
        print (read_execution_count(execution_count_filename))

if __name__ == "__main__":
    # If this confuses you - visit: 
    # https://stackoverflow.com/questions/419163/what-does-if-name-main-do
    main()
    
# Output: 

# Running some func
# 1
# Running some func
# 2
# Running some func
# 3
# Running some func
# 4
# Running some func
# 5
# Running some func
# 6
# Running some func
# 7
# Running some func
# 8
# Running some func
# 9
# Running some func
# 10

All this said, the proper way to record ("log") information generated by/during your code's execution is using logging. See this answer for more.

Reasons:
  • Blacklisted phrase (1): StackOverflow
  • Blacklisted phrase (1): stackoverflow
  • Whitelisted phrase (-1): In your case
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
Posted by: Vin