简体   繁体   中英

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? Ie 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?

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})

The simplest thing is to just change the bzr module, but then you have to remember the changes you made if you upgrade, which is a terrible thing to need to do.

The second simplest thing I can think of is to write a script that sets up the environment that bazaar needs and then calls whatever function that is the bzr entry point. You could call it 'mybzr.py' and use it by calling python -m mybzr

Skeleton contents of mybzr.py:

if __name__ == '__main__':
    # Do whatever stuff you wanted to do to change bazaar's environment.
    # You might need to alter sys.path so that you can `import bzr`.
    import bzr
    bzr.main() # I don't actually know what the function is called...

This is only a rough outline, since I don't actually know anything about bazaar. Hopefully it's a little bit helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM