Search code examples
pythonpython-2.7bazaar

How can I execute a bunch of Python commands before a script is run when using the Python interpreter?


I have a defective version of bzr which I invoked using python -m pdb $(which bzr) ... to find out what the defect is.

The defect is inside a certain module and I'd like to work around the defect by executing a command right before the python binary starts interpreting the contents of $(which bzr) (which of course is a Python script itself).

Is there a way to smuggle in code right before the script is executed? I.e. as if my smuggled in code was at the top of said script file ...

The point here is that I want to be able to use the workaround without being able to write to the bzr "binary" in question (non-root).


Attempt of a comparison

NB: please do not take the following comparison to literal. The issue with the bzr module is not a missing function. The problem is more subtle and requires reloading sys plus some other stuff.

In terms of Bash imagine the faulty script to be:

#!/bin/bash
missing_function TEST

the function does not exist, so invoking the script yields:

$ ./faulty.sh
./faulty.sh: line 2: missing_function: command not found

However, if I want to be sneaky, I can abuse source or declare the function like this in an alternative file fixed.sh:

#!/bin/bash
function missing_function
{
        echo "$@"
}
source ./faulty.sh

Executing this, yields a more meaningful result:

$ ./fixed.sh
TEST

Is there a similar technique for Python or can I somehow leverage the -m <module> option for the purpose, by hijacking a script similar to how pdb seems to do it?

How would I go about it?


Solution

  • See my example below.

    In faulty.py:

    print 'calling missing_function'
    missing_function()
    

    In fixed.py:

    def missing_function():
        print 'missing'
    execfile('faulty.py',  {'missing_function' : missing_function})