I'd like to create a log for a Python script execution. For example:
import pandas as pd
data = pd.read_excel('example.xlsx')
data.head()
How can I create a log for this script un order to know who run the script, when was executed, when did it finish. And ir for example, suppossing I take a sample of the df, how can I make to create a seed so I can share it to another person to execute it and have the same result?
You could use the
loggingmodule that comes by default with Python. You'll have to add a few extra lines of code to configure it to log the information you require (time of execution and user executing the script) and specify a file name where the log messages should be stored at.In respect to adding the information of "who" ran the script, it will depend on how you want to differentiate users. If your script is intended to be executed on some server, you might want to differentiate users by their IP addresses. Another solution is to use the
getpassmodule, like I did in the example below.Finally, when generating a sample from
data, you can set an integer as seed to the parameterrandom_stateto make the sample always contain the same rows.Here's a modified version of your script with the previously mentioned changes:
Running the above code prints to the console the following messages:
It also creates or updates a file named
'script_execution.log', located at the same directory as the script with the same information that gets printed to the console.