Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Fix missing import with a monkey patch

I am trying to monkey patch a missing import. The old_invoke() still does not get the import.
In case it is relevant, MyClass is a gdb.Command.

(gdb) pi
>>> import mymodule
>>> old_invoke = mymodule.MyClass.invoke
>>> def new_invoke(self, *k, **kw):
...   print("New invoke")
...   import getopt
...   old_invoke(self, *k, **kw)
...
>>> mymodule.MyClass.invoke = new_invoke
>>>
(gdb) my_gdb_command
New invoke
Python Exception <class 'NameError'> name 'getopt' is not defined:
Error occurred in Python: name 'getopt' is not defined

Also, in case it is relevant, the initial files and sourcing looks something like this:

mymodule.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import gdb
class MyClass(gdb.Command):
   ...

   def invoke(self, arg, from_tty):
      options, remainder = getopt.getopt(args, 'p:s:t:o:')
      ...

MyClass()

myothermodule.py:

import mymodule
...

Sourcing the above

(gdb) source myothermodule.py

>Solution :

old_invoke is trying to reference mymodule‘s getopt, which doesn’t exist. You need:

>>> import mymodule
>>> old_invoke = mymodule.MyClass.invoke
>>> def new_invoke(self, *k, **kw):
...   print("New invoke")
...   import getopt
...   
...   # here
...   mymodule.getopt = getopt
...   
...   old_invoke(self, *k, **kw)
...
>>> mymodule.MyClass.invoke = new_invoke

But, realistically, you should just have an import getopt in mymodule:

# mymodule.py
import getopt
...

Then your function is simply:

>>> import mymodule
>>> old_invoke = mymodule.MyClass.invoke
>>> def new_invoke(self, *k, **kw):
...   print("New invoke")
...   old_invoke(self, *k, **kw)
...
>>> mymodule.MyClass.invoke = new_invoke
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading