Mathieu Fenniak’s Weblog

viagra generic canada
viagra cheap generic
viagra softabs
real viagra woman
viagra cialis canadian pharmacy
generic viagra tab
sales online viagra
online medications viagra
viagra cost in canada
viagra 50 mg
order viagra or levitra
viagra argentina
viagra online pharamcy
viagra cheap sale
viagra 100mg dosage
viagra generic on line
order viagra cialis levitra pharmacy
order viagra without prescription
sale viagra
online perscriptions for viagra
viagra generic soft tabs 100mg
sales uk viagra
viagra cost
viagra cialis store
online viagra for sale
low cost viagra
where to buy viagra in london
viagra cheap online rx
get viagra now internet
online pharmacy prescription drug viagra
viagra price uk
viagra prescriptions uk
viagra buy general
viagra uk without prescription
where can i purchase viagra
viagra buy it
viagra to buy
viagra best prices
order cialis and viagra
viagra in usa
order prescription viagra without
viagra cheapest uk
where to purchase viagra
viagra on internet prescription online
viagra get prescription online
get viagra in canada
viagra price online
viagra online without prescription
order viagra prescription
viagra soft tabs low cialis
viagra buy australia
purchase viagra without prescription
online cheap viagra
purchasing viagra australia
viagra without perscription
lowest price on viagra
viagra cheapest price
no online pharmacy prescription required viagra
viagra canada prescription
viagra on line no prescripton
generic viagra solf tabs
purchase viagra soft tabs
purchasing viagra in venezuela
viagra by mail canada
online store viagra
no prescription order viagra online
viagra buying online
viagra generic discount
viagra on line sales
viagra genetic
us discount viagra
on line generic viagra for sale
online order viagra
viagra united states
viagra usa mastercard
online viagra prescription canada
viagra online
viagra cialis canada
viagra cialis online
viagra cialis online pharmacy satisfaction guaranteed
ordering generic viagra in canada
viagra online rx
generic viagra rx
viagra canada generic
non prescription viagra
where to get viagra
viagra in the uk
mail order viagra online
where to buy viagra uk
viagra in mexico
viagra online no rx
online pill viagra
get viagra drug online
viagra cheapest prices
viagra on line purchase
online uk viagra sales
uk viagra on line
viagra cheap prescription
online viagra canada
get viagra without prescription
viagra uk cheap
viagra prices in usa
viagra cost uk
viagra best buy
viagra 100mg
viagra on the internet
online ordering viagra
low price for viagra
order viagra here
generic viagra uk
viagra cialis buy no prescription
viagra prescription order
no prescription viagra
uk viagra sales online
viagra discount sales
order viagra without a prescription
purchase cheap viagra online
purchase viagra professional
viagra cheap
generic viagra pills
purchase viagra by check
viagra 100mg tablets
uk viagra online
online viagra pharmacy
viagra pharmacy sales london
on line pharmacy for viagra
viagra canadian price shipped
viagra on line order
generic viagra without visa
viagra in uk
order mexican viagra
online viagra no generic
mail order viagra in uk
viagra pharmacy online
viagra in britain
where can i buy viagra in
viagra to order
order viagra now viagra money order
order 50mg viagra
no rx viagra
viagra no presrciption
lowest viagra prices
viagra to buy in uk
viagra 50mg
viagra cheapest
viagra buy in uk online
lowest price generic viagra
viagra online no doctor prescription
order viagra online no rx prescription
viagra cost best price viagra
viagra purchase
viagra generico impotencia
purchasing viagra in mexico
viagra prescriptions online
order generic viagra online
viagra canada
where can i get viagra
sales of viagra
viagra cheap uk
viagra buy generic
getting viagra in the philippines
mail order viagra uk
viagra online ordering
order viagra overnight delivery
generic viagra softabs
online viagra
sale online viagra
viagra with out prescription
viagra in australia
order viagra online
real viagra online for americans
us drugs store cheap viagra
viagra without prescription new york
generic viagra with money order
viagra pills online
viagra no prior prescription
where to buy viagra
mail uk viagra
lowest priced viagra in britain
viagra cialis online pharmacy
viagra 100 50 25
non prescription viagra in uk
viagra online shop
viagra canida
viagra generic uk
online viagra order
uk viagra kamagra
get viagra without a prescription
order generic viagra
viagra by mail
generic viagra soft pharmacy online
pharmacy purchase viagra
viagra without prescription
viagra american express canada
lowest cost of viagra
viagra best price generic
viagra online canada
lowest cost viagra
viagra cost per pill
generic viagra sale
viagra uk retail price
viagra online pharmacies
generic viagra us licensed online pharmacy
generic viagra us pharmacy
on viagra
viagra 25mg
viagra prescriptions on line
viagra canada satisfaction guarantee
viagra without presciption online
uk viagra prices
viagra prescription uk
online shop viagra
sales viagra
get viagra
viagra online store
ordering viagra
get viagra now no doctor visit
where to buy viagra online
order viagra canada
uk viagra sales
viagra germany
viagra cost australia
viagra by the pill
get viagra online
where do i buy viagra online
purchase viagra in uk
viagra on prescription
generic viagra propecia
viagra to buy uk
viagra online discount
viagra best price
where to buy viagra from
generic viagra sales
non perscription viagra
no perscription viagra
on line pharmacy viagra
viagra without precription
online viagra sales
viagra cheap buy
viagra canada price
where can i buy viagra on
viagra by overnight delivery
viagra 50mg or 100mg
viagra 50mg uk
ordering viagra without prescription
get viagra prescription online
get viagra now
online viagra pills
viagra in the philippines
viagra online stores
tadalafil viagra
viagra soft tabs generic 100mg
purchasing viagra online
viagra 100
pharmacy viagra
viagra uk sales
viagra 50mg 100mg
viagra canada online
order viagra softtabs
on line generic viagra
viagra 25
no persription viagra
viagra generic cheap
where to buy viagra in nz
viagra soft tab
purchase viagra and cialis
online pharmacy viagra no prescription
viagra pill on line
online generic viagra sales
online parmacy viagra cheap
viagra on line
viagra best price sildenafil
order viagra on line
viagra cialis no prescription required
online sales viagra
no prescription cheap viagra
viagra in netherland
order discount viagra
uk cheapest viagra
viagra buy viagra
viagra purchase uk
nonprescription viagra
viagra buy oonline
viagra uk cheap purchase buy
viagra cheap no prescription
viagra best prices fda approved
viagra price australia
order viagra usa
no online order prescription viagra
viagra soft tab generic
viagra online pharmacy
viagra on line prescription
viagra discounts
viagra uk buy
viagra 50mg online
lowest price viagra online
pure theatrical viagra
where can i buy viagra online
online viagra australia
low price viagra
low priced viagra chain store
viagra purchase canada
online viagra levitra cialis
where can i purchase viagra online
ordering viagra online
viagra pills for sale
viagra buy online
purchasing viagra online for cheap
viagra cialis on line
viagra online cheap
online prescription for viagra
viagra no prescreption
lowest priced viagra in the uk
non perscription generic viagra
viagra on line canada
viagra canada online pharmacy
online pharmacy viagra
viagra generic buy
viagra canadian
viagra by money order
viagra generic buy online american express
viagra buy it online now
viagra prices uk
lowest price for viagra online
viagra generic cialis
where can i buy viagra uk
viagra non prescription
viagra online fda
viagra pills cheap
purchasing viagra
online free sample viagra canada
viagra without a prescription
viagra on lilne
low priced viagra
viagra cheap canada
purchase generic viagra uk
order viagra now money
viagra online purchase
non prescription viagra online
viagra pill uk
viagra pills uk
viagra price canada
viagra pills without a prescription
viagra to buy online
on line viagra american pharmacy
purchase viagra on line
viagra online shop uk
viagra online in canada
viagra pharmacy online sale
where buy viagra
online uk viagra
purchase viagra uk
generic viagra purchase
online buy viagra
viagra cheap mexico
sales online viagra sale
viagra uk online
lowest viagra price
viagra buy
viagra online without rx
viagra cialis generic
lowest cost generic viagra
viagra online prescriptions
viagra in ontario
online pharmacy uk viagra
viagra online shop online approval
online check payment viagra
viagra no prescription needed
viagra usa
viagra online prescription
order viagra overnight shipping
uk viagra
where can i order generic viagra
viagra generico mexico
lowest prices viagra
low cost viagra online
on line prescription viagra
online generic viagra
online viagra sale
real viagra
viagra without a perscription
mail order for viagra tablets
viagra 50
where can i buy viagra
no online prescription viagra
get viagra dont visit a doctor
generic viagra softtabs
order viagra viagra online
order viagra
viagra costs australia
generic viagra soft tabs
viagra to florida
online purchase viagra
viagra soft tablets
where to buy viagra on line
uk generic viagra
viagra on-line
online viagra uk
purchase viagra online
viagra best buy diet pills
viagra online uk no generic
online viagra prescriptions
tadalafil cialis vs viagra
lowest prices viagra uk
uk pharmacies cheap viagra
viagra generic cheap discounted cheapest online
viagra purchases
viagra online uk
low cost generic viagra
online viagra prescription
viagra no prescripsion
order viagra viagra
viagra online from us pharmacys
viagra best quality lowest prices
viagra cost per pill in mexico
generic viagra with american express
online order prescription viagra
on line viagra
generic viagra woman
viagra purchase online
viagra on line uk
viagra onlin
mail order viagra
where can i buy viagra from
viagra 50 mg or 100mg
online pharmacy prescription viagra
mail order viagra without prescription
lowest prices on generic viagra
viagra online no prescription
generic viagra usa
viagra amsterdam
viagra cialis online sales
order viagra cheap
viagra canadian prescriptions
tadalafil generic viagra
get discount viagra online
us viagra cheap
where do i buy viagra in
viagra u s pharmacies
viagra buy now pay later
viagra generic mastercard precription
viagra discount sale
order viagra licensed pharmacies online
viagra canadaian prices
viagra online in united states
uk viagra london
viagra no prescription canada
viagra in spain
non-prescription viagra
viagra prescription onlin
viagra online sales
online prescription viagra without
order viagra online uk
purchase generic viagra
viagra uk sale
viagra buying
viagra discount
viagra online canadiain
viagra 100 mg
get viagra on internet
lowest price viagra
low priced purchase viagra
viagra best prices fda approved online
online pharmacy viagra cialis
viagra discount online
purchase viagra in australia
order viagra on-line
order uk viagra
viagra purchase on line
viagra soft tablet
order viagra uk
viagra prescription online
viagra without prescription canada
viagra buy viagra online
viagra cheap usa
online viagra store
viagra 100mg 90 pills
where to get viagra samples
viagra in canada
where to buy viagra in uk
generic viagra sale on line
viagra softtabs
viagra generic buy american express
online pharmacy propecia viagra
viagra cialis cheap
online sale viagra
get online viagra
viagra cheap online
viagra no prescription
viagra onlines
viagra no presciption
pharmacy online viagra
mail order generic viagra
viagra 50mg soft tab generic
sale uk viagra
lowest price viagra in the uk
generic viagra online pharmacy
viagra american express
where can i get free viagra
viagra without a prescriotion
no perscription generic viagra
viagra online buy
on-line viagra
viagra cialis prescription online
viagra philippines
viagra on sale
viagra online shop in uk
order prescription viagra
viagra uk delivery
purchase generic viagra online
viagra by mail order
viagra buy uk
viagra generic drug
viagra uk purchase
purchase of viagra
viagra canada pharmacy
viagra online uk delivery
us viagra
viagra online order
generic viagra uk online pharmacy
viagra generic sildenafil
order cheap viagra
viagra purchase in united states
get viagra online guarantee
generic viagra tadalafil
order viagra onlines
nonperscription viagra
order viagra with mastercard
mail online order viagra
generic viagra pill
viagra discount store
generic viagra soft tab
viagra onliine
online phamacy viagra
viagra soft tabs
viagra on line pharmacy
online prescription viagra
purchase viagra
viagra uk
viagra generico
order viagra now

Embedding Python Tips

Filed under: programming, python, moo — Mathieu Fenniak @ March 30, 2004 2:46 am

Python is a beautiful programming language. One of it’s most wonderful features is a very clean and simple C API that allows Python to be extended with dynamically loadable C modules. That same C API also allows Python to be embedded in other pieces of software. This means that any program can allow the user to enter Python code interactively (or otherwise) to affect the program in whatever way they wish. This is a powerful capability, but using occasionally requires a few tricks to accomplish the embedder’s goals.

Today’s embedding exercise was allowing a MOO server to execute arbitrary Python code:

;py_runfunction({"import math", "return math.sqrt(2*2*2)"})
> 2.8284271247461903

Of course, a MOO server can already do square roots… that wasn’t the point. There was no point. Anyways, here are a few ideas that might help other people embed Python in a useful way.

Evaluating Statements

One of the first things most people try to do is evaluate an arbitrary statement and get its return value. This is not quite as easy as it sounds. Although Python’s eval builtin does this, it may be more limited than the embedding programmer desires. eval will only permit an expression to be evaluated, not a statement:

>>> eval("x = 2")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    x = 2
      ^
SyntaxError: invalid syntax

I suggest that if you want the user to be able to evaluate an arbitrary block of code, wrap an artificial function around it and call the function itself:

def f():
    import math
    class Cylinder:
        def _calcVolume(self):
            return math.pi * 
                self.radius**2 * 
                self.height
        volume = property(_calcVolume)
    c = Cylinder()
    c.radius = 12.2
    c.height = 16.12
    return c.volume

This allows the user to input much more complex functions, like the above example which uses a class and an import statement. All that needed to be artificially added was the ‘def f():’ and an arbitrary but constant amount of whitespace in front of each line of code.

Compiling Code without a Module

So you’ve gotten some code from a user, and you want to compile it. Maybe you’re creating a function to wrap around the user’s code. Where does that function belong? Where do you evaluate your code?

The first instinct I had was to use PyImport_AddModule to get the __main__ module and start importing functions into its module dictionary. I had a block of code similar to this (error checking omitted):

Py_Initialize();
PyObject* module = PyImport_AddModule("__main__");
PyObject* moduleDict = PyModule_GetDict(module);
PyObject* compileRetval = PyRun_String(code, Py_file_input,
    moduleDict, moduleDict);
...
Py_Finalize();

This then allowed me to call functions on the module object and get some code back. The only real downside was the initialize and finalize around my code. I didn’t want code from one compile to mess with another, and since I was using the __main__ module, this caused problems. Eventually I decided to use random strings as the names for my modules so that I could use them all independently, but that sure was ugly.

The solution I stumbled upon was caused by my accidently deleting some lines of code. I eventually realized that I didn’t need the module object at all. I could create a new, empty dictionary, and compile the code ‘into’ that:

PyObject* dict = PyDict_New();
PyObject* compileRetval = PyRun_String(code, Py_file_input,
    dict, dict);

Everything continued to work as before, except now I had to PyDict_GetItem out of dict and use PyObject_CallObject rather than the PyObject_CallMethod that I could have used before. But nothing crashed, the world continued to run, and I no longer needed to initialize and finalize around my evaluation. Yay!

Settings __builtins__

There was one minor problem. Some functionality like builtin functions and classes (like Exception) was missing. Oops:

// Check for __builtins__...
if (PyDict_GetItemString(dict, "__builtins__") == NULL)
{
    // Hm... no __builtins__ eh?
    PyObject* builtinMod = PyImport_ImportModule("__builtin__");
    if (builtinMod == NULL ||
        PyDict_SetItemString(dict, "__builtins__", builtinMod) != 0)
    {
        Py_DECREF(dict);
        Py_XDECREF(dict);
        // error handling
        return;
    }
    Py_DECREF(builtinMod);
}

Hey, that fixed that right up.

I had this problem when I was using random names for modules, as well. It seems PyImport_AddModule does not set __builtins__ on a new module — but it is set up on __main__ always.

Getting Tracebacks using the traceback Module

What happened when things went wrong? Well, at first, a lot of crashing. And things were going wrong a lot, especially when I was trying to use modules that didn’t exist in the system. Heh heh.

Thankfully, Python will setup tracebacks that are useful even when you’re using the C API and screwing things up from the inside. How on earth do you get at those tracebacks, though? You can get a lot of information from the PyErr_* class of functions, but not a properly formatted Python traceback to display to the user. Eventually, I ended up using the traceback module itself to display an error:

char* getPythonTraceback()
{
    // Python equivilant:
    // import traceback, sys
    // return "".join(traceback.format_exception(sys.exc_type,
    //    sys.exc_value, sys.exc_traceback))

    PyObject *type, *value, *traceback;
    PyObject *tracebackModule;
    char *chrRetval;

    PyErr_Fetch(&type, &value, &traceback);

    tracebackModule = PyImport_ImportModule("traceback");
    if (tracebackModule != NULL)
    {
        PyObject *tbList, *emptyString, *strRetval;

        tbList = PyObject_CallMethod(
            tracebackModule,
            "format_exception",
            "OOO",
            type,
            value == NULL ? Py_None : value,
            traceback == NULL ? Py_None : traceback);

        emptyString = PyString_FromString("");
        strRetval = PyObject_CallMethod(emptyString, "join",
            "O", tbList);

        chrRetval = strdup(PyString_AsString(strRetval));

        Py_DECREF(tbList);
        Py_DECREF(emptyString);
        Py_DECREF(strRetval);
        Py_DECREF(tracebackModule);
    }
    else
    {
        chrRetval = strdup("Unable to import traceback module.");
    }

    Py_DECREF(type);
    Py_XDECREF(value);
    Py_XDECREF(traceback);

    return chrRetval;
}

Of course, when one can’t import the traceback module, one can’t generate a traceback explaining why not. :-)

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

Powered by WordPress