1

I am writing a package that automatically collects program execution metadata including the time program execution began and terminated.

The Python standard library exposes a hook to have code run automatically at interpreter termination via atexit.register. Using this to record a termination time is sufficient for my needs.

Since this approach will record, approximately, the time interpreter execution terminates, I would like the corresponding begin time to be approximately the time interpreter execution begins.

Is it possible to determine this time within a Python module?

  • 1
    The code to register some code to run is code as well. You can't run code before the interpreter is launched. So without some kind of time travel, not sure how that would be possible... The closest you can get IMO is recording the time in a module, and finagle that module to be very early in the load order... – Amadan Jul 19 '17 at 23:15
  • @Amadan Absolutely, it's okay if it's not the precise launch time. What I'm looking for is a hook like PYTHONSTARTUP for the interactive interpreter, or a variable like sys.argv. Ideally, the recorded times should be independent of the occurence of the package import in the source code. – Roland Maio Jul 19 '17 at 23:59

1 Answers1

1

I found a package psutil that provides a way to get the start time of the Python process in this answer https://stackoverflow.com/a/4559733 to the question How to retrieve the process start time (or uptime) in python. Usage is given in the answer.

This has the advantage of being cross-platform, but the disadvantage of introducing a dependency. That is acceptable for my use case. My package can first try to use psutil, and failing that, fall back on the current time as an approximation.

I am writing this answer because I think this solution can be helpful to others, but I'd still love to know whether or not there is a way to get the Python interpreter start time through the Python built-ins or standard library.