Breaking python code when opening a specific file

I want to run the code in the debugger and stop it when I open the file. I want to do this regardless of the method by which the file was opened. AFAIK there are two ways to open a file (if there is more in that case than I want to stop the code) and I want to stop the code when one of them is executed:

with open(filename, "wb") as outFile:

      

or

object = open(file_name [, access_mode][, buffering])

      

is this possible with pdb

or ipdb

?

PS: I don't know the line where the file opens, if I know I can set the breakpoint manually. Also I could grep

for open(

and set a breakpoint on the lines found, but if my code uses modules this can be problematic. Also if the file is opened in a different way not with open

(I don't know if it's possible to just guess, maybe to add, etc.), it won't work.

+3


source to share


2 answers


Ideally, you would put a breakpoint in an open inline function, but that is not possible. Instead, you can override it and place a breakpoint there:

import __builtin__

def open(name, mode='', buffer=0):
    return __builtin__.open(name, mode, buffer) # place a BreakPoint here

      

Of course, you will break yourself in any file opening, not just what you need.



So, you can refine this bit and put a conditional breakpoint:

import ipdb
import __builtin__

def open(name, mode='', buffer=0):
    if name == 'myfile.txt':
        ipdb.set_trace()  ######### Break Point ###########
    return __builtin__.open(name, mode, buffer)

f = open('myfile.txt', 'r')

      

Start your python program with python -m pdb prog.py

.

+2


source


If you don't know where the open call is, you need to fix the original one as soon as possible open

(like __main__

-guard) like this:



 import __builtin__

 _old_open = open

 def my_open(*args, **kwargs):
     print "my_open"
     return _old_open(*args, **kwargs)

 setattr(__builtin__, 'open', my_open)

 print open(__file__, "rb").read()

      

+2


source







All Articles