Question

I have a Python script but I don't want to change it. I want to use another script to modify the original one and call to run the original one with all the "print" or "time.sleep" statements being commentted out(not run). I search for it and find a method using AST, but I really don't have a idea of how to use it. Thank you very much!

Était-ce utile?

La solution

You might be able to manipulate the AST to achieve that, but it would probably be easier to monkeypatch whatever objects it uses prior to running. In your specific example, to incapacitate print and time.sleep, you could do this:

def insomniac(duration):
    pass  # don't sleep

_original_sleep = time.sleep
time.sleep = insomniac

def dont_write(stuff):
    pass  # don't write

_original_write = sys.stdout.write
sys.stdout.write = dont_write

To get the functionality back, you can set the relevant functions back to the stored originals. If you want to be truer to your original intention such that calls to these functions from the script in question are nullified but calls from other modules still work, you can inspect the stack to see what module the caller is in and selectively call the original or ignore the call.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top