2

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?

user3326078
  • 617
  • 1
  • 9
  • 19
  • To my knowledge there is no way to accomplish this without some sort of logging/writing to file. I'm just curious as to why you'd want this with such a limitation? – n1c9 Jul 27 '18 at 19:33
  • you could have it communicate with some other process, like a server, and have it keep track. However, if the server went down you would lose your info. It would be much easier to use a file. – Luke B Jul 27 '18 at 19:36
  • It doesn't have to be written specifically to a file, but the information has to be stored _somewhere_. Could be memory, file, database, etc. – Marcel Wilson Jul 27 '18 at 20:07
  • 1
    @n1c9 I am writing some Selenium scripts. I just wanted to see if a short and sweet script can exist to keep track of this. I guess data has to be stored somewhere. Might as well write to a file I guess. – user3326078 Jul 27 '18 at 22:07

1 Answers1

4

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.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • This would only work if the script didn't produce any other output. It also assumes that the script will always be run from a POSIX-compliant shell. – chepner Jul 27 '18 at 20:53
  • @chepner It's just an example, one can always redirecting output `eval $(python example.py 2>&1 >/dev/null)` and print the `MY_COUNTER` to stderr (or to some other file descriptor) – Andrej Kesely Jul 27 '18 at 20:59
  • @AndrejKesely Cool answer, thanks! I think for my Selenium scripting purpose, this will do. I just want to run a script, come back 20 minutes later and see how many times it ran. I don't need to save it. – user3326078 Jul 27 '18 at 22:11
  • Pretty clever to use env variables for this! – n1c9 Jul 30 '18 at 15:16