Search code examples
pythonoperating-systemexecutioncountingatexit

Is it possible to keep track of how many times a Python Script has been ran without writing to a file?


I am curious whether it is possible to keep track of the number of times a specific .py file is ran without ever reading and writing to/from a file.

This thread: how can i count how many time program has been executed in python

uses atexit module to update a json file and log the number of times the script has ran in its lifetime. I guess this type of data must be logged in a file?


Solution

  • Using one example how to set environment variables from Why can't environmental variables set in python persist?:

    You can have script, which sets environment variable in parent shell:

    import pipes
    import os
    value = int(os.environ['MY_COUNTER']) + 1 if 'MY_COUNTER' in os.environ else 1
    print("export MY_COUNTER=%s" % (pipes.quote(str(value))))
    

    and run this script with command:

    eval $(python example.py)
    

    Then each run will increment MY_COUNTER by 1.

    Of course, this environment variable will not persists, it's only in memory.