Command before saving a file

Hi all
I want to make a code by the python that Runs the command before saving a file.
for example
the user runs the command and after that moment at any time the user press save or want to save the file, the script run, such as changing new object layer or any thing.

I know it should be loop that run in Rhino to check every moment if the user start saving a file or not. but I dont know how to make it.

import scriptcontext as sc
import Rhino
def OnBeginSaveDocument(sender, e):
    Rhino.RhinoApp.WriteLine("document save operation begins")
if "BSDHandler" in sc.sticky:
    sc.doc.BeginSaveDocument -= sc.sticky["BSDHandler"]
sc.sticky["BSDHandler"] = OnBeginSaveDocument
sc.doc.BeginSaveDocument += sc.sticky["BSDHandler"]

BeginSaveDocument.py (331 Bytes)

Thanks for your reply but still didnt get it how it works.

what is sender and e ?
should I put it in a loop ?

Hope this help:

Thank you.

Best regards