id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
6,000 | class parsepage(htmlparser)def handle_starttag(selftagattrs)print('tag start:'tagattrsdef handle_endtag(selftag)print('tag end'tagdef handle_data(selfdata)print('data 'data rstrip()nowcreate web page' html text stringwe hardcode one herebut it might also be loaded from fileor fetched from website with urllib requestpage ""spamclick this ""finallykick off the parse by feeding text to parser instance--tags in the html text trigger class method callbackswith tag names and attribute sequences passed in as argumentsparser parsepage(parser feed(pagedata tag starthtml [data tag starth [data spamtag endh data tag startp [data click this tag starta [('href''data python tag enda data link tag endp data tag endhtml as you can seethe parser' methods receive callbacks for events during the parse much like sax xml parsingyour parser class will need to keep track of its state in attributes as it goes if it wishes to do something more specific than print tag namesattributesand content watching for specific tagscontentthoughmight be as simple as checking names and setting state flags moreoverbuilding object trees to reflect the page' structure during the parse would be straightforward text and language |
6,001 | here' another html parsing examplein we used simple method exported by this module to unquote html escape sequences ( entitiesin strings embedded in an html reply pageimport cgihtml parser cgi escape(" hello" ' < < >hello</ >html parser htmlparser(unescape( ' hellothis works for undoing html escapesbut that' all when we saw this solutioni implied that there was more general approachnow that you know about the method callback model of the html parser classthe more idiomatic way to handle entities during parse should make sense--simply catch entity callbacks in parser subclassand translate as neededclass parse(html parser htmlparser)def handle_data(selfdata)print(dataend=''def handle_entityref(selfname)map dict(lt=''print(map[name]end='' parse( feed( )print( hello better stillwe can use python' related html entities module to avoid hardcoding entity-to-character mappings for html entities this module defines many more entity names than the simple dictionary in the prior example and includes all those you'll likely encounter when parsing html text in the wilds ' < < >hello</ >from html entities import entitydefs class parse(html parser htmlparser)def handle_data(selfdata)print(dataend=''def handle_entityref(selfname)print(entitydefs[name]end='' parse( feed( )print( hello strictly speakingthe html entities module is able to map entity name to unicode code point and vice versaits table used here simply converts code point integers to characters with chr see this module' documentationas well as its source code in the python standard library for more details xml and html parsing |
6,002 | now that you understand the basic principles of the html parser class in python' standard librarythe plain text extraction module used by ' pymailgui (example - will also probably make significantly more sense (this was an unavoidable forward reference which we're finally able to closerather than repeating its code herei'll simply refer you back to that exampleas well as its self-test and test input filesfor another example of html parsing in python to study on your own it' essentially minor elaboration on the examples herewhich detects more types of tags in its parser callback methods because of space concernswe have to cut short our treatment of html parsing hereas usualknowing that it exists is enough to get started for more details on the apiconsult the python library manual and for additional html supportcheck the web for the status of third-party html parser packages like those mentioned in advanced language tools if you have background in parsing theoryyou may know that neither regular expressions nor string splitting is powerful enough to handle more complex language grammars roughlyregular expressions don' have the stack "memoryrequired by true language grammarsand so cannot support arbitrary nesting of language constructs--nested if statements in programming languagefor instance in factthis is why the xml and html parsers of the prior section are required at allboth are languages of potentially arbitrary nestingwhich are beyond the scope of regular expressions in general from theoretical perspectiveregular expressions are really intended to handle just the first stage of parsing--separating text into componentsotherwise known as lexical analysis though patterns can often be used to extract data from texttrue language parsing requires more there are number of ways to fill this gap with pythonpython as language tool in most applicationsthe python language itself can replace custom languages and parsers--user-entered code can be passed to python for evaluation with tools such as eval and exec by augmenting the system with custom modulesuser code in this scenario has access to both the full python language and any applicationspecific extensions required in sensesuch systems embed python in python since this is common python rolewe'll revisit this approach later in this custom language parsersmanual or toolkit for some sophisticated language analysis tasksthougha full-blown parser may still be required such parsers can always be written by handbut since python is built for integrating toolswe can write integrations to traditional parser generator systems such as yacc and bisontools that create parsers from language text and language |
6,003 | interfaces to such common parser generators are freely available in the open source domain (run web search for up-to-date details and linksin additiona number of python-specific parsing systems are available on the web among themply is an implementation of lex and yacc parsing tools in and for pythonthe kwparsing system is parser generator written in pythonpyparsing is pure-python class library that makes it easy to build recursive-descent parsers quicklyand the spark toolkit is lightweight system that employs the earley algorithm to work around technical problems with lalr parser generation (if you don' know what that meansyou probably don' need to careof special interest to this yapps (yet another python parser systemis parser generator written in python it uses supplied grammar rules to generate human-readable python code that implements recursive descent parserthat isit' python code that generates python code the parsers generated by yapps look much like (and were inspired bythe handcoded custom expression parsers shown in the next section yapps creates ll( parserswhich are not as powerful as lalr parsers but are sufficient for many language tasks for more on yappssee natural language processing even more demanding language analysis tasks require techniques developed in artificial intelligence researchsuch as semantic analysis and machine learning for instancethe natural language toolkitor nltkis an open source suite of python libraries and programs for symbolic and statistical natural language processing it applies linguistic techniques to textual dataand it can be used in the development of natural language recognition software and systems for much more on this subjectbe sure to also see the 'reilly book natural language processing with pythonwhich exploresamong other thingsways to use nltk in python not every system' users will pose questions in natural languageof coursebut there are many applications which can make good use of such utility though widely usefulparser generator systems and natural language analysis toolkits are too complex for us to cover in any sort of useful detail in this text consult python orgor search the web for more information on language analysis tools available for use in python programs for the purposes of this let' move on to explore more basic and manual approach that illustrates concepts underlying the domain-recursive descent parsing lesson don' reinvent the wheel (usuallyspeaking of parser generatorsto use some of these tools in python programsyou'll need an extension module that integrates them the first step in such scenarios should always be to see whether the extension already exists in the public domain especially for common tools like thesechances are that someone else has already implemented an integration that you can use off-the-shelf instead of writing one from scratch advanced language tools |
6,004 | but there' growing library of available components that you can pick up for free and community of experts to query visit the pypi site at to python software resourcesor search the web at large with at least one million python users out there as write this bookmuch can be found in the prior-art department unlessof coursethe wheel does not workwe've also seen handful of cases in this book where standard libraries were either not adequate or were broken altogether for instancethe python email package issues we explored in required us to code workarounds of our own in such casesyou may still ultimately need to code your own infrastructure support the "not invented heresyndrome can still claim victory when software dependencies break down stillyou're generally better off trying to use the standard support provided by python in most caseseven if doing so requires manually coded fixes in the email package examplefixing its problems seems much easier than coding an email parser and generator from scratch-- task far too large to have even attempted in this book python' batteries included approach to development can be amazingly productive--even when some of those batteries require charge custom language parsers although toolkits abound in this domainpython' status as general-purpose programming language also makes it reasonable vehicle for writing hand-coded parsers for custom language analysis tasks for instancerecursive descent parsing is fairly well-known technique for analyzing language-based information though not as powerful as some language toolsrecursive descent parses are sufficient for wide variety of language-related goals to illustratethis section develops custom parser for simple grammar--it parses and evaluates arithmetic expression strings though language analysis is the main topic herethis example also demonstrates the utility of python as general-purpose programming language although python is often used as frontend or rapid development language in tactical modesit' also often useful for the kinds of strategic work you may have formerly done in systems development language such as or +the expression grammar the grammar that our parser will recognize can be described as followsgoal -end goal -end [numbervariable[setassign -'set[setexpr -[numbervariable text and language |
6,005 | expr-tail -'+expr-tail -'-[end[+[-factor -[numbervariablefactor-tail -factor-tail -'*factor-tail -'/[+-end[*[/term -term -term -'(')[number[variable[(tokens()numvar-+/*setend this is fairly typical grammar for simple expression languageand it allows for arbitrary expression nesting (some example expressions appear at the end of the test parser module listing in example - strings to be parsed are either an expression or an assignment to variable name (setexpressions involve numbersvariablesand the operators +-*and because factor is nested in expr in the grammarand have higher precedence ( they bind tighterthan and expressions can be enclosed in parentheses to override precedenceand all operators are left associative-that isthey group on the left ( is treated the same as ( - )- tokens are just the most primitive components of the expression language each grammar rule listed earlier is followed in square brackets by list of tokens used to select it in recursive descent parsingwe determine the set of tokens that can possibly start rule' substringand we use that information to predict which rule will work ahead of time for rules that iterate (the -tail rules)we use the set of possibly following tokens to know when to stop typicallytokens are recognized by string processor ( scanner)and higher-level processor ( parseruses the token stream to predict and step through grammar rules and substrings the parser' code the system is structured as two modulesholding two classesthe scanner handles low-level character-by-character analysis the parser embeds scanner and handles higher-level grammar analysis the parser is also responsible for computing the expression' value and testing the system in this versionthe parser evaluates the expression while it is being parsed to use the systemwe create parser with an input string and call its parse method we can also call parse again later with new expression string there' deliberate division of labor here the scanner extracts tokens from the stringbut it knows nothing about the grammar the parser handles the grammarbut it is custom language parsers |
6,006 | and it' another example of the object-oriented programming (oopcomposition relationship at workparsers embed and delegate to scanners the module in example - implements the lexical analysis task--detecting the expression' basic tokens by scanning the text string left to right on demand notice that this is all straightforward logicsuch analysis can sometimes be performed with regular expressions instead (described earlier)but the pattern needed to detect and extract tokens in this example would be too complex and fragile for my tastes if your tastes varytry recoding this module with re example - pp \lang\parser\scanner py ""##############################################################################the scanner (lexical analyser##############################################################################""import string class syntaxerror(exception)pass class lexicalerror(exception)pass local errors used to be strings class scannerdef __init__(selftext)self next self text text '\ def newtext(selftext)scanner __init__(selftextdef showerror(self)print('='self textprint('='(self start'^'def match(selftoken)if self token !tokenraise syntaxerror(tokenelsevalue self value if self token !'\ 'self scan(return value next token/value return prior value def scan(self)self value none ix self next while self text[ixin string whitespaceix + self start ix if self text[ixin ['('')''-''+''/''*''\ ']self token self text[ixix + text and language |
6,007 | str 'while self text[ixin string digitsstr +self text[ixix + if self text[ix='str +ix + while self text[ixin string digitsstr +self text[ixix + self token 'numself value float(strelseself token 'numself value int(strsubsumes long(in elif self text[ixin string ascii_lettersstr 'while self text[ixin (string digits string ascii_letters)str +self text[ixix + if str lower(='set'self token 'setelseself token 'varself value str elseraise lexicalerror(self next ix the parser module' class creates and embeds scanner for its lexical chores and handles interpretation of the expression grammar' rules and evaluation of the expression' resultas shown in example - example - pp \lang\parser\parser py ""###############################################################################the parser (syntax analyserevaluates during parse###############################################################################""class undefinederror(exception)pass from scanner import scannerlexicalerrorsyntaxerror class parserdef __init__(selftext='')self lex scanner(textself vars {'pi' def parse(self*text)if textembed scanner add variable main entry-point custom language parsers |
6,008 | reuse this parsertryself lex scan(get first token self goal(parse sentence except syntaxerrorprint('syntax error at column:'self lex startself lex showerror(except lexicalerrorprint('lexical error at column:'self lex startself lex showerror(except undefinederror as ename args[ print("'%sis undefined at column:nameself lex startself lex showerror(def goal(self)if self lex token in ['num''var''(']val self expr(self lex match('\ 'print(valelif self lex token ='set'self assign(self lex match('\ 'elseraise syntaxerror(def assign(self)self lex match('set'var self lex match('var'val self expr(self vars[varval expressionset commandassign name in dict def expr(self)left self factor(while trueif self lex token in ['\ '')']return left elif self lex token ='+'self lex scan(left left self factor(elif self lex token ='-'self lex scan(left left self factor(elseraise syntaxerror(def factor(self)left self term(while trueif self lex token in ['+''-''\ '')']return left elif self lex token ='*'self lex scan(left left self term(elif self lex token ='/' text and language |
6,009 | left left self term(elseraise syntaxerror(def term(self)if self lex token ='num'val self lex match('num'return val elif self lex token ='var'if self lex value in self vars keys()val self vars[self lex valueself lex scan(return val elseraise undefinederror(self lex valueelif self lex token ='('self lex scan(val self expr(self lex match(')'return val elseraise syntaxerror(if __name__ ='__main__'import testparser testparser test(parser'parser 'numbers keys()eibtilook up name' value sub-expression self-test code test local parser if you study this code closelyyou'll notice that the parser keeps dictionary (self varsto manage variable namesthey're stored in the dictionary on set command and are fetched from it when they appear in an expression tokens are represented as stringswith an optional associated value ( numeric value for numbers and string for variable namesthe parser uses iteration (while loopsrather than recursion for the expr-tail and factor-tail rules other than this optimizationthe rules of the grammar map directly onto parser methodstokens become calls to the scannerand nested rule references become calls to other methods when the file parser py is run as top-level programits self-test code is executedwhich in turn simply runs canned test in the module shown in example - notice how the scanner converts numbers to strings with intthis ensures that all integer math invoked by the parser supports unlimited precisionsimply because it uses python integers which always provide the extra precision if needed (the separate python long type and syntax is no morealso notice that mixed integer/floating-point operations cast up to floating point since python operators are used to do the actual calculations along the way the expression language' division operator also inherits python ' true division model which retains remainders and returns floating point results regardless of operand types we custom language parsers |
6,010 | both and /in our grammar)but we'll follow python ' lead here example - pp \lang\parser\testparser py ""###########################################################################parser test code ###########################################################################""def test(parserclassmsg)print(msgparserclassx parserclass(' ' parse( parse(' ' parse('( ' parse(' ( )' parse(' ( )' parse(' ( )' parse(' ' parse('( ' parse(' ( )' parse('((( )) 'allow different parsers like eval(' ' xis now true div /is not supported (yety parserclass( parse('set ' parse(' ' parse('set ' parse(' ' parserclass( parse('set ' parse('set ' parse(' ' parserclass( parse('pi' parse(' pi' parse(' 'def interact(parserclass)print(parserclassx parserclass(while truecmd input('enter='if cmd ='stop'break parse(cmdcommand-line entry correlate the following results to print call statements in the self-test modulec:\pp \lang\parserpython parser py parser text and language |
6,011 | as usualwe can also test and use the system interactively to work through more of its utilityc:\pp \lang\parserpython import parser parser parser( parse(' ' error cases are trapped and reported in fairly friendly fashion (assuming users think in zero-based terms) parse(' ''ais undefined at column = = parse(' + + ''ais undefined at column = + + = parse(' $'lexical error at column = = parse(' 'syntax error at column = = parse(' ( 'syntax error at column = ( = parse(' ' parse(' / 'syntax error at column = / = division change custom language parsers |
6,012 | as the custom parser system demonstratesmodular program design is almost always major win by using python' program structuring tools (functionsmodulesclassesand so on)big tasks can be broken down into smallmanageable parts that can be coded and tested independently for instancethe scanner can be tested without the parser by making an instance with an input string and calling its scan or match methods repeatedly we can even test it like this interactivelyfrom python' command line when we separate programs into logical componentsthey become easier to understand and modify imagine what the parser would look like if the scanner' logic was embedded rather than called pathologically big numbers are handled welltoobecause python' built-in objects and operators are used along the wayx parse(' ' + parse(' ' parse(' ' + in additionthere is an interactive loop interface in the testparser module if you want to use the parser as simple command-line calculator (or if you get tired of typing parser method callspass the parser classso testparser can make one of its ownimport testparser testparser interact(parser parserenter= enter= enter=( enter=set enter=set enter= enter= lexical error at column = =enter= 'cis undefined at column = =enter= syntax error at column = =enter= text and language |
6,013 | enter= enter=stop adding parse tree interpreter one weakness in the parser program is that it embeds expression evaluation logic in the parsing logicthe result is computed while the string is being parsed this makes evaluation quickbut it can also make it difficult to modify the codeespecially in larger systems to simplifywe could restructure the program to keep expression parsing and evaluation separate instead of evaluating the stringthe parser can build up an intermediate representation of it that can be evaluated later as an added incentivebuilding the representation separately makes it available to other analysis tools ( optimizersviewersand so on)--they can be run as separate passes over the tree example - shows variant of parser that implements this idea the parser analyzes the string and builds up parse tree--that isa tree of class instances that represents the expression and that may be evaluated in separate step the parse tree is built from classes that "knowhow to evaluate themselvesto compute the expressionwe just ask the tree to evaluate itself root nodes in the tree ask their children to evaluate themselvesand then combine the results by applying single operator in effectevaluation in this version is simply recursive traversal of tree of embedded class instances constructed by the parser example - pp \lang\parser\parser py ""separate expression parsing from evaluation by building an explicit parse tree ""tracedefault false class undefinederror(exception)pass if __name__ ='__main__'from scanner import scannersyntaxerrorlexicalerror elsefrom scanner import scannersyntaxerrorlexicalerror if run here from pytree ################################################################################the interpreter ( smart objects tree################################################################################class treenodedef validate(selfdict)pass def apply(selfdict)pass def trace(selflevel)print(level ''default error check default evaluator default unparser custom language parsers |
6,014 | class binarynode(treenode)def __init__(selfleftright)inherited methods self leftself right leftright left/right branches def validate(selfdict)self left validate(dictrecurse down branches self right validate(dictdef trace(selflevel)print(level '[self label ']'self left trace(level+ self right trace(level+ class timesnode(binarynode)label '*def apply(selfdict)return self left apply(dictself right apply(dictclass dividenode(binarynode)label '/def apply(selfdict)return self left apply(dictself right apply(dictclass plusnode(binarynode)label '+def apply(selfdict)return self left apply(dictself right apply(dictclass minusnode(binarynode)label '-def apply(selfdict)return self left apply(dictself right apply(dictleaves class numnode(treenode)def __init__(selfnum)self num num already numeric def apply(selfdict)use default validate return self num def trace(selflevel)print(level repr(self num)as codewas 'self numclass varnode(treenode)def __init__(selftextstart)self name text variable name self column start column for errors def validate(selfdict)if not self name in dict keys()raise undefinederror(self nameself columndef apply(selfdict)return dict[self namevalidate before apply def assign(selfvaluedict)dict[self namevalue local extension text and language |
6,015 | print(level self namecomposites class assignnode(treenode)def __init__(selfvarval)self varself val varval def validate(selfdict)self val validate(dictdon' validate var def apply(selfdict)self var assignself val apply(dict)dict def trace(selflevel)print(level 'set 'self var trace(level self val trace(level ################################################################################the parser (syntax analysertree builder################################################################################class parserdef __init__(selftext='')self lex scanner(textself vars {'pi': self traceme tracedefault def parse(self*text)if textself lex newtext(text[ ]tree self analyse(if treeif self tracemeprint()tree trace( if self errorcheck(tree)self interpret(treemake scanner add constants external interface reuse with new text parse string dump parse-treecheck names evaluate tree def analyse(self)tryself lex scan(get first token return self goal(build parse-tree except syntaxerrorprint('syntax error at column:'self lex startself lex showerror(except lexicalerrorprint('lexical error at column:'self lex startself lex showerror(def errorcheck(selftree)trytree validate(self varserror checker return 'okexcept undefinederror as instanceargs is tuple varinfo instance args print("'%sis undefined at column%dvarinfocustom language parsers |
6,016 | self lex showerror(def interpret(selftree)result tree apply(self varsif result !noneprint(resultreturns none tree evals itself ignore 'setresult ignores errors def goal(self)if self lex token in ['num''var''(']tree self expr(self lex match('\ 'return tree elif self lex token ='set'tree self assign(self lex match('\ 'return tree elseraise syntaxerror(def assign(self)self lex match('set'vartree varnode(self lex valueself lex startself lex match('var'valtree self expr(return assignnode(vartreevaltreetwo subtrees def expr(self)left self factor(while trueif self lex token in ['\ '')']return left elif self lex token ='+'self lex scan(left plusnode(leftself factor()elif self lex token ='-'self lex scan(left minusnode(leftself factor()elseraise syntaxerror(def factor(self)left self term(while trueif self lex token in ['+''-''\ '')']return left elif self lex token ='*'self lex scan(left timesnode(leftself term()elif self lex token ='/'self lex scan(left dividenode(leftself term()elseraise syntaxerror( text and language left subtree add root-node grows up/right |
6,017 | if self lex token ='num'leaf numnode(self lex match('num')return leaf elif self lex token ='var'leaf varnode(self lex valueself lex startself lex scan(return leaf elif self lex token ='('self lex scan(tree self expr(self lex match(')'return tree elseraise syntaxerror(################################################################################self-test codeuse my parserparser ' tester ################################################################################if __name__ ='__main__'import testparser testparser test(parser'parser 'run with parser class here notice the way we handle undefined name exceptions in errorcheck when exceptions are derived from the built-in exception classtheir instances automatically return the arguments passed to the exception constructor call as tuple in their args attribute-convenient for use in string formatting here also notice that the new parser reuses the same scanner module as well to catch errors raised by the scannerit also imports the specific classes that identify the scanner' exceptions both the scanner and the parser can raise exceptions on errors (lexical errorssyntax errorsand undefined name errorsthey're caught at the top level of the parserand they end the current parse there' no need to set and check status flags to terminate the recursion since math is done using integersfloating-point numbersand python' operatorsthere' usually no need to trap numeric overflow or underflow errors but as isthe parser doesn' handle errors such as division by zero--such python exceptions make the parser system exit with python stack trace and message uncovering the cause and fix for this is left as suggested exercise when parser is run as top-level programwe get the same test code output as for parser in factit reuses the very same test code--both parsers pass in their parser class object to testparser test and since classes are also objectswe can also pass this version of the parser to testparser' interactive looptestparser interact(parser parserthe new parser' external behavior is identical to that of the originalso won' repeat all its output here (run this live for firsthand lookof notethoughthis parser supports both use as top-level scriptand package imports from other directoriessuch as the pytree viewer we'll use in moment python no longer searches module' custom language parsers |
6,018 | import syntax for the latter caseand import from another directory when testing interactivelyc:\pp \lang\parserparser py parser rest is same as for parser :pp \lang\parserpython import parser from scanner import scannersyntaxerrorlexicalerror valueerrorattempted relative import in non-package from pytree :\pp \lang\parsercd :\pp \langparser\parser py parser rest is same as for parser :\pp \langpython from parser import parser parser parser( parse(' ' import parser testparser parser testparser interact(parser parserenter= enter=stop using full package import paths in parser instead of either package-relative or unqualified importsfrom pp lang parser import scanner would suffice for all three use cases--scriptand both same and other directory imports--but requires the path to be set properlyand seems overkill for importing file in the same directory as the importer parse tree structure reallythe only tangible difference with this latest parser is that it builds and uses trees to evaluate an expression internally instead of evaluating as it parses the intermediate representation of an expression is tree of class instanceswhose shape reflects the order of operator evaluation this parser also has logic to print an indented listing of the constructed parse tree if the traceme attribute is set to true (or indentation gives the nesting of subtreesand binary operators list left subtrees first for examplec:\pp \langfrom parser import parser text and language |
6,019 | traceme true parse(' '[+ [* when this tree is evaluatedthe apply method recursively evaluates subtrees and applies root operators to their results hereis evaluated before +since it' lower in the tree the factor method consumes the substring before returning right subtree to expr the next tree takes different shapep parse(' '[-[* in this exampleis evaluated before the factor method loops through substring of and expressions before returning the resulting left subtree to expr the next example is more complexbut follows the same rulesp parse(' ( )'[+ [* [+[* trees are made of nested class instances from an oop perspectiveit' another way to use composition since tree nodes are just class instancesthis tree could be created and evaluated manuallytooplusnodenumnode( )timesnodenumnode( )plusnodetimesnode(numnode( )numnode( ))numnode( ))apply({}but we might as well let the parser build it for us (python is not that much like lispdespite what you may have heardcustom language parsers |
6,020 | but wait--there is better way to explore parse tree structures figure - shows the parse tree generated for the string ( )displayed in pytreethe tree visualization gui described at the end of this works only because the parser module builds the parse tree explicitly (parser evaluates during parse insteadand because pytree' code is generic and reusable figure - pytree view of parse tree built for ( if you read the last you'll recall that pytree can draw most any tree data structurebut it is preconfigured to handle binary search trees and the expression parse trees we're studying in this for parse treesclicking on nodes in displayed parse tree evaluates the subtree rooted there text and language |
6,021 | tree shape produced for given expressionstart pytreeclick on its parser radio buttontype the expression in the input field at the bottom rightand press "input(or your enter keythe parser class is run to generate tree from your inputand the gui displays the result depending on the operators used within an expressionsome very differently shaped trees yield the same result when evaluated try running pytree on your computer to get better feel for the parsing process ( ' like to show more example treesbut ran out of page real estate at this point in the book parsers versus python the handcoded custom parser programs we've met in this section illustrate some interesting concepts and underscore the power of python for general-purpose programming depending on your job descriptionthey may also be typical of the sort of thing you' write regularly in traditional language such as parsers are an important component in wide variety of applicationsbut in some casesthey're not as necessary as you might think let me explain why so farwe started with an expression parser and added parse tree interpreter to make the code easier to modify as isthe parser worksbut it may be slow compared to implementation if the parser is used frequentlywe could speed it up by moving parts to extension modules for instancethe scanner might be moved to initiallysince it' often called from the parser ultimatelywe might add components to the grammar that allow expressions to access application-specific variables and functions all of these steps constitute good engineering but depending on your applicationthis approach may not be the best one in python often the easiest way to evaluate input expressions in python is to let python do it for usby calling its eval built-in function in factwe can usually replace the entire expression evaluation program with this one function call the next section will show how this can be used to simplify languagebased systems in general more importantthe next section underscores core idea behind the languageif you already have an extensibleembeddablehigh-level language systemwhy invent anotherpython itself can often satisfy language-based component needs pycalca calculator program/object to wrap up this ' going to show you practical application for some of the parsing technology introduced in the preceding section this section presents pycalca python calculator program with graphical interfacesimilar to the calculator programs available on most window systems like most of the gui examples in this bookthoughpycalc offers few advantages over existing calculators because pycalc is pycalca calculator program/object |
6,022 | platforms and because it is implemented with classesit is both standalone program and reusable object library simple calculator gui before show you how to write full-blown calculatorthoughthe module shown in example - starts this discussion in simpler terms it implements limited calculator guiwhose buttons just add text to the input field at the top in order to compose python expression string fetching and running the string all at once produces results figure - shows the window this module makes when run as top-level script example - pp \lang\calculator\calc py " simplistic calculator guiexpressions run all at once with eval/execfrom tkinter import from pp gui tools widgets import framebuttonentry class calcgui(frame)def __init__(selfparent=none)frame __init__(selfparentself pack(expand=yesfill=bothself master title('python calculator 'self master iconname("pcalc "self names {text stringvar(entry(selftoptextan extended frame on default top-level all parts expandable frames plus entry namespace for variables rows ["abcd"" "" "" ()"for row in rowsfrm frame(selftopfor char in rowbutton(frmleftcharlambda char=chartext set(text get(char)frm frame(selftopfor char in "+-*/="button(frmleftcharlambda char=chartext set(text get()char ')frm frame(selfbottombutton(frmleft'eval'lambdaself eval(textbutton(frmleft'clear'lambdatext set(''def eval(selftext)trytext set(str(eval(text get()self namesself names))except syntaxerrortryexec(text get()self namesself namesexcept text and language was ' |
6,023 | elsetext set(''excepttext set("error"bad as statement tooworked as statement other eval expression errors if __name__ ='__main__'calcgui(mainloop(figure - the calc script in action on windows (result= building the gui nowthis is about as simple as calculator can bebut it demonstrates the basics this window comes up with buttons for entry of numbersvariable namesand operators it is built by attaching buttons to frameseach row of buttons is nested frameand the gui itself is frame subclass with an attached entry and six embedded row frames (grids would work heretoothe calculator' frameentry fieldand buttons are made expandable in the imported widgets utility module we coded earlier in example - this calculator builds up string to pass to the python interpreter all at once on "evalbutton presses because you can type any python expression or statement in the entry fieldthe buttons are really just convenience in factthe entry field isn' much more than command line try typing import sysand then dir(systo display sys module attributes in the input field at the top--it' not what you normally do with calculatorbut it is demonstrative nevertheless once againi need to warn you about running code strings like this if you can' be sure they won' cause damage if these strings can be entered by users you cannot trustthey will have access to anything on the computer that the python process has access to see and for more on security issues related to code run in guiweband other contexts pycalca calculator program/object |
6,024 | row and each character in the string represents button lambdas are used to save extra callback data for each button the callback functions retain the button' character and the linked text entry variable so that the character can be added to the end of the entry widget' current string on press notice how we must pass in the loop variable as default argument to some lambdas in this code recall from how references within lambda (or nested defto names in an enclosing scope are evaluated when the nested function is callednot when it is created when the generated function is calledenclosing scope references inside the lambda reflect their latest setting in the enclosing scopewhich is not necessarily the values they held when the lambda expression ran by contrastdefaults are evaluated at function creation time instead and so can remember the current values of loop variables without the defaultseach button would reflect the last iteration of the loop lesson embedding beats parsers the calculator uses eval and exec to call python' parser and interpreter at runtime instead of analyzing and evaluating expressions manually in effectthe calculator runs embedded python code from python program this works because python' development environment (the parser and bytecode compileris always part of systems that use python because there is no difference between the development and the delivery environmentspython' parser can be used by python programs the net effect here is that the entire expression evaluator has been replaced with single call to eval or exec in broader termsthis is powerful technique to rememberthe python language itself can replace many smallcustom languages besides saving development timeclients have to learn just one languageone that' potentially simple enough for end-user coding furthermorepython can take on the flavor of any application if language interface requires application-specific extensionsjust add python classesor export an api for use in embedded python code as extension by evaluating python code that uses application-specific extensionscustom parsers become almost completely unnecessary there' also critical added benefit to this approachembedded python code has access to all the tools and features of powerfulfull-blown programming language it can use listsfunctionsclassesexternal modulesand even larger python tools like tkinter guisshelve storagemultiple threadsnetwork socketsand web page fetches you' probably spend years trying to provide similar functionality in custom language parser just ask guido running code strings this module implements gui calculator in some lines of code (counting comments and blank linesbut truthfullyit "cheats expression evaluation is delegated entirely to python in factthe built-in eval and exec tools do most of the work here text and language |
6,025 | parsesevaluatesand returns the result of python expression represented as string exec runs an arbitrary python statement represented as stringand has no return value both accept optional dictionaries to be used as global and local namespaces for assigning and evaluating names used in the code strings in the calculatorself names becomes symbol table for running calculator expressions related python functioncompilecan be used to precompile code strings to code objects before passing them to eval and exec (use it if you need to run the same string many timesby defaulta code string' namespace defaults to the caller' namespaces if we didn' pass in dictionaries herethe strings would run in the eval method' namespace since the method' local namespace goes away after the method call returnsthere would be no way to retain names assigned in the string notice the use of nested exception handlers in the class' eval method it first assumes the string is an expression and tries the built-in eval function if that fails because of syntax errorit tries evaluating the string as statement using exec finallyif both attempts failit reports an error in the string ( syntax errorundefined nameand so onstatements and invalid expressions might be parsed twicebut the overhead doesn' matter hereand you can' tell whether string is an expression or statement without parsing it manually note that the "evalbutton evaluates expressionsbut sets python variables by running an assignment statement variable names are combinations of the letter keys "abcd(or any name typed directlythey are assigned and evaluated in dictionary used to represent the calculator' namespace and retained for the session extending and attaching clients that reuse this calculator are as simple as the calculator itself like most classbased tkinter guisthis one can be extended in subclasses--example - customizes the simple calculator' constructor to add extra widgets example - pp \lang\calculator\calc ext py from tkinter import from calc import calcgui class inner(calcgui)def __init__(self)calcgui __init__(selflabel(selftext='calc subclass'pack(button(selftext='quit'command=self quitpack(extend gui add after top implied pycalca calculator program/object |
6,026 | it can also be embedded in container class--example - attaches the simple calculator' widget packagealong with extrasto common parent example - pp \lang\calculator\calc emb py from tkinter import from calc import calcgui add parentno master calls class outerdef __init__(selfparent)embed gui label(parenttext='calc attachment'pack(side=top calcgui(parentadd calc frame button(parenttext='quit'command=parent quitpack(root tk(outer(rootroot mainloop(figure - shows the result of running both of these scripts from different command lines both have distinct input field at the top this worksbut to see more practical application of such reuse techniqueswe need to make the underlying calculator more practicaltoo figure - the calc script' object attached and extended text and language |
6,027 | of coursereal calculators don' usually work by building up expression strings and evaluating them all at oncethat approach is really little more than glorified python command line traditionallyexpressions are evaluated in piecemeal fashion as they are enteredand temporary results are displayed as soon as they are computed implementing this behavior requires bit more workexpressions must be evaluated manually and in partsinstead of calling the eval function only once but the end result is much more useful and intuitive lesson reusability is power though simpleattaching and subclassing the calculator graphicallyas shown in figure - illustrates the power of python as tool for writing reusable software by coding programs with modules and classescomponents written in isolation almost automatically become general-purpose tools python' program organization features promote reusable code in factcode reuse is one of python' major strengths and has been one of the main themes of this book good object-oriented design takes some practice and forethoughtand the benefits of code reuse aren' apparent immediately and sometimes we have good cause to be more interested in quick fix rather than future use for the code but coding with some reusability in mind can save development time in the long run for instancethe handcoded custom parsers shared scannerthe calculator gui uses the widgets module from we discussed earlierand the next section will reuse the guimixin class from as well sometimes we're able to finish part of job before we start this section presents the implementation of pycalca more realistic python/tkinter program that implements such traditional calculator gui it touches on the subject of text and languages in two waysit parses and evaluates expressionsand it implements kind of stack-based language to perform the evaluation although its evaluation logic is more complex than the simpler calculator shown earlierit demonstrates advanced programming techniques and serves as an interesting finale for this running pycalc as usuallet' look at the gui before the code you can run pycalc from the pygadgets and pydemos launcher bars at the top of the examples treeor by directly running the file calculator py listed shortly ( click it in file exploreror type it in shell command linefigure - shows pycalc' main window by defaultit shows operand buttons in black-on-blue (and opposite for operator buttons)but font and color options can be passed into the gui class' constructor method of coursethat means gray-on-gray in this bookso you'll have to run pycalc yourself to see what mean pycalca calculator program/object |
6,028 | if you do run thisyou'll notice that pycalc implements normal calculator model-expressions are evaluated as enterednot all at once at the end that isparts of an expression are computed and displayed as soon as operator precedence and manually typed parentheses allow the result in figure - for instancereflects pressing " "and then repeatedly pressing "*to display successive powers of 'll explain how this evaluation works in moment pycalc' calcgui class builds the gui interface as frames of buttons much like the simple calculator of the previous sectionbut pycalc adds host of new features among them are another row of action buttonsinherited methods from guimixin (presented in ) new "cmdbutton that pops up nonmodal dialogs for entry of arbitrary python codeand recent calculations history pop up figure - captures some of pycalc' pop-up windows you may enter expressions in pycalc by clicking buttons in the guityping full expressions in command-line pop upsor typing keys on your keyboard pycalc intercepts key press events and interprets them the same as corresponding button pressestyping is like pressing the buttonthe space bar key is "clear,enter is "eval,backspace erases characterand is like pressing "help the command-line pop-up windows are nonmodal (you can pop up as many as you likethey accept any python code--press the run button or your enter key to evaluate text in their input fields the result of evaluating this code in the calculator' namespace text and language |
6,029 | dictionary is thrown up in the main window for use in larger expressions you can use this as an escape mechanism to employ external tools in your calculations for instanceyou can import and use functions coded in python or within these pop ups the current value in the main calculator window is stored in newly opened command-line pop upstoofor use in typed expressions pycalc supports integers (unlimited precision)negativesand floating-point numbers just because python does individual operands and expressions are still evaluated with the eval built-inwhich calls the python parser/interpreter at runtime variable names can be assigned and referenced in the main window with the letter=and "evalkeysthey are assigned in the calculator' namespace dictionary (more complex variable names may be typed in command-line pop upsnote the use of pi in the history windowpycalc preimports names in the math and random modules into the namespace where expressions are evaluated evaluating expressions with stacks now that you have the general idea of what pycalc doesi need to say little bit about how it does what it does most of the changes in this calculator involve managing the expression display and evaluating expressions pycalc is structured as two classesthe calcgui class manages the gui itself it controls input events and is in charge of the main window' display field at the top it doesn' evaluate expressionsthoughfor thatit pycalca calculator program/object |
6,030 | evaluator class the evaluator class manages two stacks one stack records pending operators ( +)and one records pending operands ( temporary results are computed as new operators are sent from calcgui and pushed onto the operands stack as you can see from thisthe magic of expression evaluation boils down to juggling the operator and operand stacks in sensethe calculator implements little stack-based languageto evaluate the expressions being entered while scanning expression strings from left to right as they are enteredoperands are pushed along the waybut operators delimit operands and may trigger temporary results before they are pushed because it records states and performs transitionssome might use the term state machine to describe this calculator language implementation here' the general scenario when new operator is seen ( when an operator button or key is pressed)the prior operand in the entry field is pushed onto the operands stack the operator is then added to the operators stackbut only after all pending operators of higher precedence have been popped and applied to pending operands ( pressing makes any pending operators on the stack fire when "evalis pressedall remaining operators are popped and applied to all remaining operandsand the result is the last remaining value on the operands stack in the endthe last value on the operands stack is displayed in the calculator' entry fieldready for use in another operation this evaluation algorithm is probably best described by working through examples let' step through the entry of few expressions and watch the evaluation stacks grow pycalc stack tracing is enabled with the debugme flag in the moduleif truethe operator and operand stacks are displayed on stdout each time the evaluator class is about to apply an operator and reduce (popthe stacks run pycalc with console window to see the traces tuple holding the stack lists (operators operandsis printed on each stack reductiontops of stacks are at the ends of the lists for instancehere is the console output after typing and evaluating simple string entered keys" [result (['*'][' '' '](['+'][' '' '][on '+pressdisplays " "[on 'evalpressdisplays " "note that the pending (stackedsubexpression is evaluated when the is pressedoperators bind tighter than +so the code is evaluated immediately before the operator is pushed when the button is pressedthe entry field contains we push onto the operands stackreduce the subexpression ( )push its result onto operandspush text and language |
6,031 | is pushed onto operandsand the final on operators is applied to stacked operands the text input and display field at the top of the gui' main window plays part in this algorithmtoo the text input field and expression stacks are integrated by the calculator class in generalthe text input field always holds the prior operand when an operator button is pressed ( on *)the text in the input field is pushed onto the operands stack before the operator is resolved because of thiswe have to pop results before displaying them after "evalor is pressedotherwise the results are pushed onto the stack twice--they would be both on the stack and in the display fieldfrom which they would be immediately pushed again when the next operator is input for both usability and accuracywhen an operator is seenwe also have to arrange to erase the input field' prior value when the next operand' entry is started ( on both and in this erasure of the prior values is also arranged when "evalor is appliedon the assumption that subsequent operand key or button replaces the prior result--for new expression after "eval,and for an operand following new operator after ) to erase the parenthesized result on in ( without this erasureoperand buttons and keys simply concatenate to the currently displayed value this model also allows user to change temporary result operands after by entry of operand instead of operator expression stacks also defer operations of lower precedence as the input is scanned in the next tracethe pending isn' evaluated when the button is pressedsince binds tighterwe need to postpone the until the can be evaluated the operator isn' popped until its right operand has been seen there are two operators to pop and apply to operand stack entries on the "evalpress--the at the top of operators is applied to the and at the top of operandsand then is run on and the pushed for * entered keys" [result (['+''*'][' '' '' '](['+'][' '' '][on 'evalpress[displays " "for strings of same-precedence operators such as the followingwe pop and evaluate immediately as we scan left to rightinstead of postponing evaluation this results in left-associative evaluationin the absence of parentheses + + is evaluated as (( + )+ for and operations this is irrelevant because order doesn' matter entered keys" [result (['+'][' '' '](['+'][' '' '][on the second '+'[on 'eval'the following trace is more complex in this caseall the operators and operands are stacked (postponeduntil we press the button at the end to make parentheses workis given higher precedence than any operator and is pushed onto the operators stack to seal off lower stack reductions until the is seen when the button is pressedthe pycalca calculator program/object |
6,032 | is displayed in the entry field on pressing "eval,the rest is evaluated (( )( + ))and the final result ( is shown this result in the entry field itself becomes the left operand of future operator entered keys" [result (['+''*''(''+''*'][' '' '' '' '' '](['+''*''(''+'][' '' '' '' '](['+''*'][' '' '' '](['+'][' '' '][on ')'[displays " "[on 'eval'in factany temporary result can be used againif we keep pressing an operator button without typing new operandsit' reapplied to the result of the prior press--the value in the entry field is pushed twice and applied to itself each time press many times after entering to see how this works ( ***on the first *it pushes and the on the next *it pushes again from the entry fieldpops and evaluates the stacked ( )pushes back and displays the resultand pushes the new and on each following *it pushes the currently displayed result and evaluates againcomputing successive squares figure - shows how the two stacks look at their highest level while scanning the expression in the prior example trace on each reductionthe top operator is applied to the top two operands and the result is pushed back for the operator below because of the way the two stacks are usedthe effect is similar to converting the expression to string of the form + * (+ * and evaluating it right to left in other casesthoughparts of the expression are evaluated and displayed as temporary results along the wayso it' not simply string conversion process figure - evaluation stacks ( finallythe next example' string triggers an error pycalc is casual about error handling many errors are made impossible by the algorithm itselfbut things such as unmatched parentheses still trip up the evaluator instead of trying to detect all possible error cases explicitlya general try statement in the reduce method is used to catch them allexpression errorsnumeric errorsundefined name errorssyntax errorsand so on text and language |
6,033 | applied by calling eval when an error occurs inside an expressiona result operand of *erroris pushedwhich makes all remaining operators fail in eval too *erroressentially percolates to the top of the expression at the endit' the last operand and is displayed in the text entry field to alert you of the mistake entered keys" [result *error*(['+''*''(''+''*'][' '' '' '' '' '](['+''*''(''+'][' '' '' '' '](['+''*''('][' '' '' '](['+''*'][' ''*error*'](['+']['*error*'](['+']['*error*''*error*'][on evaltry tracing through these and other examples in the calculator' code to get feel for the stack-based evaluation that occurs once you understand the general shift/reduce (push/popmechanismexpression evaluation is straightforward pycalc source code example - contains the pycalc source module that puts these ideas to work in the context of gui it' single-file implementation (not counting utilities imported and reusedstudy the source for more detailsas usualthere' no substitute for interacting with the program on your own to get better feel for its functionality also see the opening comment' "to dolist for suggested areas for improvement like all software systemsthis calculator is prone to evolve over time (and in fact it haswith each new edition of this booksince it is written in pythonsuch future mutations will be easy to apply example - pp \lang\calculator\calculator py #!/usr/local/bin/python ""###############################################################################pycalc + python/tkinter calculator program and gui component evaluates expressions as they are enteredcatches keyboard keys for expression entry added integrated command-line popupsa recent calculations history display popupfonts and colors configurationhelp and about popupspreimported math/random constantsand more (pp eversion number retained)-port to run under python (only-drop 'lkeypress (the long type is now dead in earnest changes (pp )-use 'readonlyentry statenot 'disabled'else field is greyed out (fix for tkinter change)-avoid extended display precision for floats by using str()instead of ` `/repr((fix for python change)pycalca calculator program/object |
6,034 | -use justify=right for input field so it displays on rightnot left-add ' +and ' -buttons (and 'ekeypressfor float exponents'ekeypress must generally be followed digitsnot or optr key-remove 'lbutton (but still allow 'lkeypress)superfluous nowbecause python auto converts up if too big ('lforced this in past)-use smaller font size overall-auto scroll to the end in the history window to doadd commas-insertion mode (see str format and lp example)allow '**as an operator keyallow '+and 'jinputs for complex numbersuse new decimal type for fixed precision floatsas iscan use 'cmdpopup windows to input and evaluate things like complexbut can' be input via main windowcaveatpycalc' precisionaccuracyand some of its behaviouris currently bound by result of str(call###############################################################################""from tkinter import from pp gui tools guimixin import guimixin from pp gui tools widgets import labelentrybuttonframe fgbgfont 'black''skyblue'('courier' 'bold'widgetsconsts quit method widget builders default config debugme true def trace(*args)if debugmeprint(args###############################################################################the main class handles user interfacean extended frameon new toplevelor embedded in another container widget ###############################################################################class calcgui(guimixinframe)operators "+-*/=operands ["abcd"" "" "" ()"button lists customizable def __init__(selfparent=nonefg=fgbg=bgfont=font)frame __init__(selfparentself pack(expand=yesfill=bothall parts expandable self eval evaluator(embed stack handler self text stringvar(make linked variable self text set(" "self erase clear " text next self makewidgets(fgbgfontbuild the gui itself if not parent or not isinstance(parentframe)self master title('pycalc 'title iff owns window self master iconname("pycalc"ditto for key bindings self master bind(''self onkeyboardself entry config(state='readonly' not 'disabled'=grey elseself entry config(state='normal'self entry focus(def makewidgets(selffgbgfont) text and language frames plus text-entry |
6,035 | fontcolor configurable self entry config(font=font make display larger self entry config(justify=right on rightnot left for row in self operandsfrm frame(selftopfor char in rowbutton(frmleftcharlambda op=charself onoperand(op)fg=fgbg=bgfont=fontfrm frame(selftopfor char in self operatorsbutton(frmleftcharlambda op=charself onoperator(op)fg=bgbg=fgfont=fontfrm frame(selftopbutton(frmleft'dot 'lambdaself onoperand(')button(frmlefte'lambdaself text set(self text get()+' +')button(frmlefte'lambdaself text set(self text get()+' -')button(frmleft'cmd 'self onmakecmdlinebutton(frmleft'help'self helpbutton(frmleft'quit'self quitfrom guimixin frm frame(selfbottombutton(frmleft'eval 'self onevalbutton(frmleft'hist 'self onhistbutton(frmleft'clear'self oncleardef onclear(self)self eval clear(self text set(' 'self erase def oneval(self)self eval shiftopnd(self text get()self eval closeall(self text set(self eval popopnd()self erase last or only opnd apply all optrs left need to popoptr nextdef onoperand(selfchar)if char ='('self eval open(self text set('('clear text next self erase elif char =')'self eval shiftopnd(self text get()last or only nested opnd self eval close(pop here toooptr nextself text set(self eval popopnd()self erase elseif self eraseself text set(charclears last value elseself text set(self text get(charelse append to opnd pycalca calculator program/object |
6,036 | def onoperator(selfchar)self eval shiftopnd(self text get()self eval shiftoptr(charself text set(self eval topopnd()self erase push opnd on left eval exprs to leftpush optrshow opnd|result erased on next opnd|'(def onmakecmdline(self)new toplevel(new top-level window new title('pycalc command line'arbitrary python code frm frame(newtoponly the entry expands label(frmleft''pack(expand=novar stringvar(ent entry(frmleftvarwidth= onbutton (lambdaself oncmdline(varent)onreturn (lambda eventself oncmdline(varent)button(frmright'run'onbuttonpack(expand=noent bind(''onreturnvar set(self text get()def oncmdline(selfvarent)eval cmdline pop-up input tryvalue self eval runstring(var get()var set('okay'if value !nonerun in eval namespace dict self text set(valueexpression or statement self erase var set('okay ='valueexceptresult in calc field var set('error'status in pop-up field ent icursor(endinsert point after text ent select_range( endselect msg so next key deletes def onkeyboard(selfevent)pressed event char on keyboard press event if pressed !''pretend button was pressed if pressed in self operatorsself onoperator(pressedelsefor row in self operandsif pressed in rowself onoperand(pressedbreak else edrop 'llif pressed ='self onoperand(pressedcan start opnd if pressed in 'ee' no +/self text set(self text get()+pressedcan'tno erase elif pressed ='\ 'self oneval(enter key=eval elif pressed ='self onclear(spacebar=clear elif pressed ='\ 'self text set(self text get()[:- ]backspace text and language |
6,037 | self help(def onhist(self)show recent calcs log popup from tkinter scrolledtext import scrolledtext new toplevel(ok button(newtext="ok"command=new destroyok pack(pady= side=bottomtext scrolledtext(newbg='beige'text insert(' 'self eval gethist()text see(endtext pack(expand=yesfill=bothor pp gui tour make new window pack first=clip last add text scrollbar get evaluator text scroll to end new window goes away on ok press or enter key new title("pycalc history"new bind(""(lambda eventnew destroy())ok focus_set(make new window modalnew grab_set(get keyboard focusgrab app new wait_window(don' return till new destroy def help(self)self infobox('pycalc''pycalc +\ ' python/tkinter calculator\ 'programming python \ 'may \ '( )\ \ 'use mouse or keyboard to\ 'input numbers and operators,\ 'or type code in cmd popup'###############################################################################the expression evaluator class embedded in and used by calcgui instanceto perform calculations ###############################################################################class evaluatordef __init__(self)self names {self opndself optr [][self hist [self runstring("from math import *"self runstring("from random import *"def clear(self)self opndself optr [][if len(self hist self hist ['clear'elseself hist append('--clear--'def popopnd(self)value self opnd[- self opnd[- :[ names-space for my vars two empty stacks my prev calcs history log preimport math modules into calc' namespace leave names intact don' let hist get too big pop/return top|last opnd to display and shift next pycalca calculator program/object |
6,038 | or pop()or del [- def topopnd(self)return self opnd[- top operand (end of listdef open(self)self optr append('('treat '(like an operator def close(self)self shiftoptr(')'self optr[- :[on ')pop downto highest '(ok if emptystays empty popor added again by optr def closeall(self)while self optrforce rest on 'evalself reduce(last may be var name tryself opnd[ self runstring(self opnd[ ]exceptself opnd[ '*error*pop else added again nextafterme {'*'['+''-''(''=']'/'['+''-''(''=']'+'['(''=']'-'['(''=']')'['(''=']'='['('class member optrs to not pop for key if prior optr is thispush elsepop/eval prior optr all left-associative as is def shiftopnd(selfnewopnd)self opnd append(newopndpush opnd at optr')'eval def shiftoptr(selfnewoptr)apply ops with <priority while (self optr and self optr[- not in self afterme[newoptr])self reduce(self optr append(newoptrpush this op above result optrs assume next opnd erases def reduce(self)trace(self optrself opndtrycollapse the top expr operator self optr[- pop top optr (at end[leftrightself opnd[- :pop top opnds (at endself optr[- :[delete slice in-place self opnd[- :[result self runstring(left operator rightif result =noneresult left assignmentkey var name self opnd append(resultpush result string back exceptself opnd append('*error*'stack/number/name error def runstring(selfcode)tryresult str(eval(codeself namesself names)self hist append(code =resultexcept text and language not ` `/repr try exprstring add to hist log |
6,039 | self hist append(coderesult none return result try stmtnone def gethist(self)return '\njoin(self histdef getcalcargs()from sys import argv get cmdline args in dict config {ex-bg black -fg red for arg in argv[ :]font not yet supported if arg in ['-bg''-fg']-bg red-{'bg':'red'tryconfig[arg[ :]argv[argv index(arg exceptpass return config if __name__ ='__main__'calcgui(**getcalcargs()mainloop(in default toplevel window using pycalc as component pycalc serves standalone program on my desktopbut it' also useful in the context of other guis like most of the gui classes in this bookpycalc can be customized with subclass extensions or embedded in larger gui with attachments the module in example - demonstrates one way to reuse pycalc' calcgui class by extending and embeddingsimilar to what was done for the simple calculator earlier example - pp \lang\calculator\calculator_test py ""test calculatoruse as an extended and embedded gui component ""from tkinter import from calculator import calcgui def calccontainer(parent=none)frm frame(parentfrm pack(expand=yesfill=bothlabel(frmtext='calc container'pack(side=topcalcgui(frmlabel(frmtext='calc container'pack(side=bottomreturn frm class calcsubclass(calcgui)def makewidgets(selffgbgfont)label(selftext='calc subclass'pack(side=toplabel(selftext='calc subclass'pack(side=bottomcalcgui makewidgets(selffgbgfont#label(selftext='calc subclass'pack(side=bottompycalca calculator program/object |
6,040 | import sys if len(sys argv= calculator_test py root tk(run calcs in same process calcgui(toplevel()each in new toplevel window calccontainer(toplevel()calcsubclass(toplevel()button(roottext='quit'command=root quitpack(root mainloop(if len(sys argv= calculator_testl py calcgui(mainloop(as standalone window (default rootelif len(sys argv= calculator_test py calccontainer(mainloop(as an embedded component elif len(sys argv= calculator_test py calcsubclass(mainloop(as customized superclass figure - shows the result of running this script with no command-line arguments we get instances of the original calculator classplus the container and subclass classes defined in this scriptall attached to new top-level windows figure - the calculator_test scriptattaching and extending these two windows on the right reuse the core pycalc code running in the window on the left all of these windows run in the same process ( quitting one quits them all)but they all function as independent windows note that when running three calculators in the same process like thiseach has its own distinct expression evaluation namespace because it' class instance attributenot global module-level variable because of thatvariables set in one calculator are set in that calculator onlyand they don' overwrite settings made in other windows similarlyeach calculator has its own evaluation stack manager objectsuch that calculations in one window don' appear in or impact other windows at all text and language |
6,041 | top and bottom of the window--but the concept is widely applicable you could reuse the calculator' class by attaching it to any gui that needs calculator and customize it with subclasses arbitrarily it' reusable widget adding new buttons in new components one obvious way to reuse the calculator is to add additional expression feature buttons--square rootsinversescubesand the like you can type such operations in the command-line pop upsbut buttons are bit more convenient such features could also be added to the main calculator implementation itselfbut since the set of features that will be useful may vary per user and applicationa better approach may be to add them in separate extensions for instancethe class in example - adds few extra buttons to pycalc by embedding ( attachingit in container example - pp \lang\calculator\calculator_plus_emb py ""############################################################################ container with an extra row of buttons for common operationsa more useful customizationadds buttons for more operations (sqrt /xetc by embedding/compositionnot subclassingnew buttons are added after entire calgui frame because of the packing order/options############################################################################""from tkinter import from calculator import calcguigetcalcargs from pp gui tools widgets import framebuttonlabel class calcguiplus(toplevel)def __init__(self**args)toplevel __init__(selflabel(selftop'pycalc plus container'self calc calcgui(self**argsfrm frame(selfbottomextras [('sqrt''sqrt(% )')(' ^ ''(% )** ')(' ^ ''(% )** ')(' / '' /(% )')for (labexprin extrasbutton(frmleftlab(lambda expr=exprself onextra(expr))button(frmleftpi 'self onpidef onextra(selfexpr)text self calc text eval self calc eval trytext set(eval runstring(expr text get())excepttext set('error'pycalca calculator program/object |
6,042 | self calc text set(self calc eval runstring('pi')if __name__ ='__main__'root tk(button(roottop'quit'root quitcalcguiplus(**getcalcargs()mainloop(-bg,-fg to calcgui because pycalc is coded as python classyou can always achieve similar effect by extending pycalc in new subclass instead of embedding itas shown in example - example - pp \lang\calculator\calculator_plus_ext py ""############################################################################ customization with an extra row of buttons for common operationsa more useful customizationadds buttons for more operations (sqrt /xetc by subclassing to extend the original classnot embeddingnew buttons show up before frame attached to bottom by calcgui class############################################################################""from tkinter import from calculator import calcguigetcalcargs from pp gui tools widgets import labelframebutton class calcguiplus(calcgui)def makewidgets(self*args)label(selftop'pycalc plus subclass'calcgui makewidgets(self*argsfrm frame(selfbottomextras [('sqrt''sqrt(% )')(' ^ ''(% )** ')(' ^ ''(% )** ')(' / '' /(% )')for (labexprin extrasbutton(frmleftlab(lambda expr=exprself onextra(expr))button(frmleftpi 'self onpidef onextra(selfexpr)tryself text set(self eval runstring(expr self text get())exceptself text set('error'def onpi(self)self text set(self eval runstring('pi')if __name__ ='__main__'calcguiplus(**getcalcargs()mainloop(passes -bg-fg on notice that these buttonscallbacks force floating-point division to be used for inverses just because that' how operates in python (/for integers truncates remainders text and language |
6,043 | issues they could instead convert the entry' text to number and do real mathbut python does all the work automatically when expression strings are run raw also note that the buttons added by these scripts simply operate on the current value in the entry fieldimmediately that' not quite the same as expression operators applied with the stacks evaluator (additional customizations are needed to make them true operatorsstillthese buttons prove the point these scripts are out to make--they use pycalc as componentboth from the outside and from below finallyto test both of the extended calculator classesas well as pycalc configuration optionsthe script in example - puts up four distinct calculator windows (this is the script run by pydemosexample - pp \lang\calculator\calculator_plusplus py #!/usr/local/bin/python ""demo all calculator flavors at once each is distinct calculator object and window ""from tkinter import tkbuttontoplevel import calculatorcalculator_plus_extcalculator_plus_emb root=tk(calculator calcgui(toplevel()calculator calcgui(toplevel()fg='white'bg='purple'calculator_plus_ext calcguiplus(toplevel()fg='gold'bg='black'calculator_plus_emb calcguiplus(fg='black'bg='red'button(roottext='quit calcs'command=root quitpack(root mainloop(figure - shows the result--four independent calculators in top-level windows within the same process the two windows on the right represent specialized reuses of pycalc as componentand the help dialog appears in the lower right although it may not be obvious in this bookall four use different color schemescalculator classes accept color and font configuration options and pass them down the call chain as needed as we learned earlierthese calculators could also be run as independent processes by spawning command lines with the launchmodes module we met in in factthat' how the pygadgets and pydemos launcher bars run calculatorsso see their code for more details and as alwaysread the code and experiment on your own for further enlightenmentthis is pythonafter all pycalca calculator program/object |
6,044 | this concludes our python language material in this book the next and final technical of the text takes us on tour of techniques for integrating python with programs written in compiled languages like and +not everyone needs to know how to do thisso some readers may wish to skip ahead to the book' conclusion in at this point since most python programmers use wrapped libraries (even if they don' wrap them themselves)thoughi recommend quick pass over the next before you close the book on this book text and language |
6,045 | in closinghere' less tangible but important aspect of python programming common remark among new users is that it' easy to "say what you meanin python without getting bogged down in complex syntax or obscure rules it' programmer-friendly language in factit' not too uncommon for python programs to run on the first attempt as we've seen in this bookthere are number of factors behind this distinction--lack of declarationsno compile stepssimple syntaxuseful built-in objectspowerful librariesand so on python is specifically designed to optimize speed of development (an idea we'll expand on in for many usersthe end result is remarkably expressive and responsive languagewhich can actually be fun to use for real work for instancethe calculator programs of this were initially thrown together in one afternoonstarting from vagueincomplete goals there was no analysis phaseno formal designand no official coding stage typed up some ideas and they worked moreoverpython' interactive nature allowed me to experiment with new ideas and get immediate feedback since its initial developmentthe calculator has been polished and expanded muchof coursebut the core implementation remains unchanged naturallysuch laid-back programming mode doesn' work for every project sometimes more upfront design is warranted for more demanding taskspython has modular constructs and fosters systems that can be extended in either python or and simple calculator gui may not be what some would call "serioussoftware development but maybe that' part of the pointtoo pycalca calculator program/object |
6,046 | python/ integration " am lost at cthroughout this bookour programs have all been written in python code we have used interfaces to services outside pythonand we've coded reusable tools in the python languagebut all our work has been done in python itself despite our programsscale and utilitythey've been python through and through for many programmers and scriptersthis mode makes perfect sense in factsuch standalone programming is one of the main ways people apply python as we've seenpython comes with batteries included--interfaces to system toolsinternet protocolsguisdata storageand much more is already available moreovermost custom tasks we're likely to encounter have prebuilt solutions in the open source worldthe pil systemfor exampleallows us to process images in tkinter guis by simply running self-installer but for some systemspython' ability to integrate with components written in (or compatible withthe programming language is crucial feature in factpython' role as an extension and interface language in larger systems is one of the reasons for its popularity and why it is often called "scriptinglanguage in the first place its design supports hybrid systems that mix components written in variety of programming languages because different languages have different strengthsbeing able to pick and choose on component-by-component basis is powerful concept you can add python to the mix anywhere you need flexible and comparatively easy-to-use language toolwithout sacrificing raw speed where it matters compiled languages such as and +are optimized for speed of executionbut are complex to program--for developersand especially for end users who need to tailor programs because python is optimized for speed of developmentusing python scripts to control or customize software components written in or +can yield more flexible systemsquicker executionand faster development modes for examplemoving selected components of pure python program to can optimize program performance moreoversystems designed to delegate customizations to python code |
6,047 | complex or proprietary languages in this last technical of this bookwe're going to take brief look at tools for interfacing with -language componentsand discuss both python' ability to be used as an embedded language tool in other systemsand its interfaces for extending python scripts with new modules implemented in -compatible languages we'll also briefly explore other integration techniques that are less specificsuch as jython notice that said "briefin the preceding paragraph because not all python programmers need to master this topicbecause it requires studying language code and makefilesand because this is the final of an already in-depth bookthis omits details that are readily available in both python' standard manual setand the source code of python itself insteadhere we'll take quick look at handful of basic examples to help get you started in this domainand hint at the possibilities they imply for python systems extending and embedding before we get to any codei want to start out by defining what we mean by "integrationhere although that term can be interpreted almost as widely as "object,our focus in this is on tight integration--where control is transferred between languages by simpledirectand fast in-process function call although it is also possible to link components of an application less directly using ipc and networking tools such as sockets and pipes that we explored earlier in the bookwe are interested in this part of the book in more direct and efficient techniques when you mix python with components written in (or other compiled languages)either python or can be "on top because of thatthere are two distinct integration modes and two distinct apisthe extending interface for running compiled library code from python programs the embedding interface for running python code from compiled programs extending generally has three main rolesto optimize programs--recoding parts of program in is last-resort performance boostto leverage existing libraries--opening them up for use in python code extends their reachand to allow python programs to do things not directly supported by the language--python code cannot normally access devices at absolute memory addressesfor instancebut can call functions that do for examplethe numpy package for python is largely an instance of extending at workby integrating optimized numeric librariesit turns python into flexible and efficient system for numeric programming that some compare to matlab python/ integration |
6,048 | python codea system can be modified without shipping or building its full source code for instancesome programs provide python customization layer that can be used to modify the program on site by modifying python code embedding is also sometimes used to route events to python-coded callback handlers python gui toolkitsfor exampleusually employ embedding in some fashion to dispatch user events figure - sketches this traditional dual-mode integration model in extendingcontrol passes from python through glue layer on its way to code in embeddingc code processes python objects and runs python code by calling python api functions because python is "on topin extendingit defines fixed integration structurewhich can be automated with tools such as swig-- code generator we'll meet in this which produces glue code required to wrap and +libraries because python is subordinate in embeddingit instead provides set of api tools which programs employ as needed figure - traditional integration model in some modelsthings are not as clear-cut for exampleunder the ctypes module discussed laterpython scripts make library calls rather than employing glue code in systems such as cython (and its pyrex predecessor)things are more different still- libraries are produced from combinations of python and code and in jython and ironpythonthe model is similarbut java and ccomponents replace the languageand the integration is largely automated we will meet such alternative systems later in this for nowour focus is on traditional python/ integration models this introduces extending firstand then moves on to explore the basics of embedding although we will study these topics in isolationkeep in mind that many systems combine the two techniques for instanceembedded python code run from can also import and call linked-in extensions to interface with the enclosing application and in callback-based systemsc libraries initially accessed through extending interfaces may later use embedding techniques to run python callback handlers on events " am lost at |
6,049 | bookwe called out to library through the extending api when our gui' user later clicked those buttonsthe gui library caught the event and routed it to our python functions with embedding although most of the details are hidden to python codecontrol jumps often and freely between languages in such systems python has an open and reentrant architecture that lets you mix languages arbitrarily for additional python/ integration examples beyond this booksee the python source code itselfits modules and objects directories are wealth of code resources most of the python built-ins we have used in this book--from simple things such as integers and strings to more advanced tools such as filessystem callstkinterand dbm files--are built with the same structures we'll introduce here their utilization of integration apis can be studied in python' source code distribution as models for extensions of your own in additionpython' extending and embedding and python/ api manuals are reasonably completeand provide supplemental information to the presentation here if you plan to do integrationyou should consider browsing these as next step for examplethe manuals go into additional details about extension typesc extensions in threaded programsand multiple interpreters in embedded programswhich we will largely bypass here extending python in coverview because python itself is coded in todaycompiled python extensions can be coded in any language that is compatible in terms of call stacks and linking that includes cbut also +with appropriate "extern cdeclarations (which are automatically provided in python header filesregardless of the implementation languagethe compiled python extensions language can take two formsc modules libraries of tools that look and feel like python module files to their clients types multiple instance objects that behave like standard built-in types and classes generallyc extension modules are used to implement flat function librariesand they wind up appearing as importable modules to python code (hence their namec extension types are used to code objects that generate multiple instancescarry perinstance state informationand may optionally support expression operators just like python classes extension types can do anything that built-in types and python-coded classes canmethod callsadditionindexingslicingand so on to make the interface workboth modules and types must provide layer of "gluecode that translates calls and data between the two languages this layer registers python/ integration |
6,050 | layer is responsible for converting arguments passed from python to form and for converting results from to python form python scripts simply import extensions and use them as though they were really coded in python because code does all the translation workthe interface is very seamless and simple in python scripts modules and types are also responsible for communicating errors back to pythondetecting errors raised by python api callsand managing garbage-collector reference counters on objects retained by the layer indefinitely--python objects held by your code won' be garbage-collected as long as you make sure their reference counts don' fall to zero once codedc modules and types may be linked to python either statically (by rebuilding pythonor dynamically (when first importedthereafterthe extension becomes another toolkit available for use in python scripts simple extension module at least that' the short storyc modules require codeand types require more of it than we can reasonably present in this although this book can' teach you development skills if you don' already have themwe need to turn to some code to make this domain more concrete because modules are simplerand because types generally export module with an instance constructor functionlet' start off by exploring the basics of module coding with quick example as mentionedwhen you add new or existing components to python in the traditional integration modelyou need to code an interface ("glue"logic layer in that handles cross-language dispatching and data translation the source file in example - shows how to code one by hand it implements simple extension module named hello for use in python scriptswith function named message that simply returns its input string argument with extra text prepended python scripts will call this function as usualbut this one is coded in cnot in python example - pp \integrate\extend\hello\hello /******************************************************************* simple extension module for pythoncalled "hello"compile this into soon python pathimport and call hello message********************************************************************#include #include /module functions *static pyobject message(pyobject *selfpyobject *argschar *frompythonresult[ ]if (pyarg_parse(args"( )"&frompython)return null/returns object */self unused in modules */args from python call */convert python - */null=raise exception * simple extension module |
6,051 | else strcpy(result"hello")strcat(resultfrompython)return py_buildvalue(" "result)/build up string */add passed python string */convert -python */registration table *static pymethoddef hello_methods[{"message"messagemeth_varargs"func doc"}{nullnull null}/name&funcfmtdoc */end of table marker */module definition structure *static struct pymoduledef hellomodule pymoduledef_head_init"hello"/name of module *"mod doc"/module documentationmay be null *- /size of per-interpreter module state- =in global vars *hello_methods /link to methods table *}/module initializer *pymodinit_func pyinit_hello(/called on first import */name matters if loaded dynamically *return pymodule_create(&hellomodule)this module has -part standard structure described by its commentswhich all modules followand which has changed noticeably in python ultimatelypython code will call this file' message functionpassing in string object and getting back new string object firstthoughit has to be somehow linked into the python interpreter to use this file in python scriptcompile it into dynamically loadable object file ( hello so on linuxhello dll under cygwin on windowswith makefile like the one listed in example - and drop the resulting object file into directory listed on your module import search path exactly as though it were py or pyc file example - pp \integrate\extend\hello\makefile hello ############################################################compile hello into shareable object file on cygwinto be loaded dynamically when first imported by python ############################################################pylib /usr/local/bin pyinc /usr/local/include/python hello dllhello gcc hello - - $(pyinc-shared - $(pylib-lpython - hello dll cleanrm - hello dll core python/ integration |
6,052 | platforms are analogous but will vary as we learned in cygwin provides unix-like environment and libraries on windows to work along with the examples hereeither install cygwin on your windows platformor change the makefiles listed per your compiler and platform requirements be sure to include the path to python' install directory with - flags to access python include ( headerfilesas well as the path to the python binary library file with - flagsif neededmine point to python ' location on my laptop after building it from its source also note that you'll need tabs for the indentation in makefile rules if cut-and-paste from an ebook substituted or dropped spaces nowto use the makefile in example - to build the extension module in example - simply type standard make command at your shell (the cygwin shell is used hereand add line break for clarity)/pp /integrate/extend/hellomake - makefile hello gcc hello - - /usr/local/include/python -shared - /usr/local/bin -lpython - hello dll this generates shareable object file-- dll under cygwin on windows when compiled this waypython automatically loads and links the module when it is first imported by python script at import timethe dll binary library file will be located in directory on the python import search pathjust like py file because python always searches the current working directory on importsthis examples will run from the directory you compile them in without any file copies or moves in larger systemsyou will generally place compiled extensions in directory listed in pythonpath or pth files insteador use python' distutils to install them in the sitepackages subdirectory of the standard library finallyto call the function from python programsimply import the module hello and call its hello message function with stringyou'll get back normal python string/pp /integrate/extend/hellopython import hello hello message('world''helloworldhello message('extending''helloextendingimport module call function and that' it--you've just called an integrated module' function from python the most important thing to notice here is that the function looks exactly as if it were coded in python python callers send and receive normal string objects from the callthe python interpreter handles routing calls to the functionand the function itself handles python/ data conversion chores in factthere is little to distinguish hello as extension module at allapart from its filename python code imports the module and fetches its attributes as if it had been written in python extension modules even respond to dir calls as usual and have the simple extension module |
6,053 | or pyc this time around--the only obvious way you can tell it' librarydir(helloc module attributes ['__doc__''__file__''__name__''__package__''message'hello __name__hello __file__ ('hello''hello dll'hello message hello hello __doc__ 'mod dochello message __doc__ 'func doca function object module object docstrings in code hello message(errors work too typeerrorargument must be sequence of length not like any module in pythonyou can also access the extension from script file the python file in example - for instanceimports and uses the extension module in example - example - pp \integrate\extend\hello\hellouse py "import and use extension library moduleimport hello print(hello message(' ')print(hello message('module hello __file__)for in range( )reply hello message(str( )print(replyrun this script as any other--when the script first imports the module hellopython automatically finds the module' dll object file in directory on the module search path and links it into the process dynamically all of this script' output represents strings returned from the function in the file hello /pp /integrate/extend/hellopython hellouse py helloc hellomodule /cygdrive/ /pp /integrate/extend/hello/hello dll hello hello hello see python' manuals for more details on the code in our moduleas well as tips for compilation and linkage of noteas an alternative to makefilesalso see the disthello py and disthello-alt py files in the examples package here' quick peek at the source code of the first of these python/ integration |
6,054 | resulting dll shows up in build subdir from distutils core import setupextension setup(ext_modules=[extension('hello'['hello '])]this is python script that specifies compilation of the extension using tools in the distutils package-- standard part of python that is used to buildinstalland distribute python extensions coded in python or distutil' larger goal is automated and portable builds and installs for distributed packagesbut it also knows how to build extensions portably systems generally include setup py which installs in sitepackages of the standard library regrettablydistutils is also too large to have survived the cleaver applied to this materialsee its two manuals in python' manuals set for more details the swig integration code generator as you can probably tellmanual coding of extensions can become fairly involved (this is almost inevitable in language worki've introduced the basics in this thus far so that you understand the underlying structure but todayc extensions are usually better and more easily implemented with tool that generates all the required integration glue code automatically there are variety of such tools for use in the python worldincluding sipswigand boost pythonwe'll explore alternatives at the end of this among thesethe swig system is widely used by python developers swig--the simplified wrapper and interface generatoris an open source system created by dave beazley and now developed by its communitymuch like python it uses and +type declarations to generate complete extension modules that integrate existing libraries for use in python scripts the generated (and ++extension modules are completethey automatically handle data conversionerror protocolsreference-count managementand more that isswig is program that automatically generates all the glue code needed to plug and +components into python programssimply run swigcompile its outputand your extension work is done you still have to manage compilation and linking detailsbut the rest of the extension task is largely performed by swig simple swig example to use swiginstead of writing the code in the prior sectionwrite the function you want to use from python without any python integration logic at allas though it is to be used from alone for instanceexample - is recoding of example - as straight function the swig integration code generator |
6,055 | /******************************************************************** simple library filewith single function"message"which is to be made available for use in python programs there is nothing about python here--this function can be called from programas well as python (with glue code*********************************************************************#include #include static char result[ ]/this isn' exported *char message(char *labelstrcpy(result"hello")strcat(resultlabel)return result/this is exported */build up string */add passed-in label */return temporary *while you're at itdefine the usual header file to declare the function externallyas shown in example - this is probably overkill for such small examplebut it will prove point example - pp \integrate\extend\hellolib\hellolib /*******************************************************************define hellolib exports to the namespacenot to python programs--the latter is defined by method registration table in python extension module' codenot by this ********************************************************************extern char *message(char *label)nowinstead of all the python extension glue code shown in the prior sectionssimply write swig type declarations input fileas in example - example - pp \integrate\extend\swig\hellolib /*****************************************************swig module description filefor lib file generate by saying "swig -python hellolib ******************************************************%module hellowrap %#include %extern char *message(char*)/or%include /hellolib/hellolib */or%include hellolib hand use - arg * python/ integration |
6,056 | description file (usually with suffixor / +header or source file interface files like this one are the most common input formthey can contain comments in or +formattype declarations just like standard header filesand swig directives that all start with for example%module sets the module' name as known to python importers %%encloses code added to generated wrapper file verbatim extern statements declare exports in normal ansi / +syntax %include makes swig scan another file (- flags give search pathsin this exampleswig could also be made to read the hellolib header file of example - directly but one of the advantages of writing special swig input files like hellolib is that you can pick and choose which functions are wrapped and exported to pythonand you may use directives to gain more control over the generation process swig is utility program that you run from your build scriptsit is not programming languageso there is not much more to show here simply add step to your makefile that runs swig and compile its output to be linked with python example - shows one way to do it on cygwin example - pp \integrate\extend\swig\makefile hellolib-swig #################################################################use swig to integrate hellolib for use in python programs on cygwin the dll must have leading "_in its name in current swig (>because also makes py without "_in its name #################################################################pylib /usr/local/bin pyinc /usr/local/include/python clib /hellolib swig /cygdrive/ /temp/swigwin-/swig the library plus its wrapper _hellowrap dllhellolib_wrap $(clib)/hellolib gcc -shared hellolib_wrap $(clib)/hellolib - $(pylib-lpython - $generated wrapper module code hellolib_wrap ohellolib_wrap $(clib)/hellolib gcc hellolib_wrap - - $(clib- $(pyinc- - $hellolib_wrap chellolib $(swig-python - $(clibhellolib the swig integration code generator |
6,057 | $(clib)/hellolib $(clib)/hellolib $(clib)/hellolib gcc $(clib)/hellolib - - $(clib- - $(clib)/hellolib cleanforcerm - dll pyc core rm - dll pyc core hellolib_wrap hellowrap py when run on the hellolib input file by this makefileswig generates two fileshellolib_wrap the generated extension module glue code file hellowrap py python module that imports the generated extension module the former is named for the input fileand the latter per the %module directive reallyswig generates two modules todayit uses combination of python and code to achieve the integration scripts ultimately import the generated python module filewhich internally imports the generated and compiled module you can wade through this generated code in the book' examples distribution if you are so inclinedbut it is prone to change over time and is too generalized to be simple to build the modulethe makefile runs swig to generate the glue codecompiles its outputcompiles the original library code if neededand then combines the result with the compiled wrapper to produce _hellowrap dllthe dll which hellowrap py will expect to find when imported by python script/pp /integrate/extend/swigdir hellolib makefile hellolib-swig /pp /integrate/extend/swigmake - makefile hellolib-swig /cygdrive/ /temp/swigwin-/swig -python - /hellolib hellolib gcc hellolib_wrap - - /hellolib - /usr/local/include/python - - hellolib_wrap gcc /hellolib/hellolib - - /hellolib - - /hellolib/hellolib gcc -shared hellolib_wrap /hellolib/hellolib - /usr/local/bin -lpython - _hellowrap dll /pp /integrate/extend/swigdir _hellowrap dll hellolib_wrap hellowrap py hellolib hellolib_wrap makefile hellolib-swig the result is dynamically loaded extension module file ready to be imported by python code like all modules_hellowrap dll mustalong with hellowrap pybe placed in directory on your python module search path (the directory where you compile will suffice if you run python there toonotice that the dll file must be built with leading underscore in its namethis is required because swig also created the py file of the same name without the underscore--if named the sameonly one could be python/ integration |
6,058 | internallyas usual in developmentyou may have to barter with the makefile to get it to work on your system once you've run the makefilethoughyou are finished the generated module is used exactly like the manually coded version shown beforeexcept that swig has taken care of the complicated parts automatically function calls in our python code are routed through the generated swig layerto the code in example - and back againwith swigthis all "just works"/pp /integrate/extend/swigpython import hellowrap hellowrap message('swig world''helloswig worldimport glue library file cwd always searched on imports hellowrap __file__ 'hellowrap pydir(hellowrap['__builtins__''__doc__''__file__''__name__''_hellowrap''message'hellowrap _hellowrap in other wordsonce you learn how to use swigyou can often largely forget the details behind integration coding in factswig is so adept at generating python glue code that it' usually easier and less error prone to code extensions for python as purely cor ++-based libraries firstand later add them to python by running their header files through swigas demonstrated here we've mostly just scratched the swig surface hereand there' more for you to learn about it from its python-specific manual--available with swig at org although its examples in this book are simpleswig is powerful enough to integrate libraries as complex as windows extensions and commonly used graphics apis such as opengl we'll apply it again later in this and explore its "shadow classmodel for wrapping +classes too for nowlet' move on to more useful extension example wrapping environment calls our next example is extension module that integrates the standard library' getenv and putenv shell environment variable calls for use in python scripts example - is file that achieves this goal in hand-codedmanual fashion example - pp \integrate\extend\cenviron\cenviron /***************************************************************** extension module for pythoncalled "cenvironwraps the library' getenv/putenv routines for use in python programs ******************************************************************wrapping environment calls |
6,059 | #include #include /***********************/ module functions */***********************static pyobject wrap_getenv(pyobject *selfpyobject *argschar *varname*varvaluepyobject *returnobj null/returns object */self not used */args from python */null=exception *if (pyarg_parse(args"( )"&varname)/python - *varvalue getenv(varname)/call getenv *if (varvalue !nullreturnobj py_buildvalue(" "varvalue)/ -python *else pyerr_setstring(pyexc_systemerror"error calling getenv")return returnobjstatic pyobject wrap_putenv(pyobject *selfpyobject *argschar *varname*varvalue*varassignpyobject *returnobj nullif (pyarg_parse(args"(ss)"&varname&varvalue)varassign malloc(strlen(varnamestrlen(varvalue )sprintf(varassign"% =% "varnamevarvalue)if (putenv(varassign= py_incref(py_none)/ call success *returnobj py_none/reference none *else pyerr_setstring(pyexc_systemerror"error calling putenv")return returnobj/**************************/ registration table */**************************static pymethoddef cenviron_methods[{"getenv"wrap_getenvmeth_varargs"getenv doc"}{"putenv"wrap_putenvmeth_varargs"putenv doc"}{nullnull null} python/ integration /name&func*/name&func*/end of table marker * |
6,060 | / module definition */*************************static struct pymoduledef cenvironmodule pymoduledef_head_init"cenviron"/name of module *"cenviron doc"/module documentationmay be null *- /size of per-interpreter module state- =in global vars *cenviron_methods /link to methods table *}/*************************/ module initializer */*************************pymodinit_func pyinit_cenviron(/called on first import */name matters if loaded dynamically *return pymodule_create(&cenvironmodule)though demonstrativethis example is arguably less useful now than it was in the first edition of this book--as we learned in part iinot only can you fetch shell environment variables by indexing the os environ tablebut assigning to key in this table automatically calls ' putenv to export the new setting to the code layer in the process that isos environ['key'fetches the value of the shell variable 'key'and os environ['key']=value assigns variable both in python and in the second action--pushing assignments out to --was added to python releases after the first edition of this book was published besides illustrating additional extension coding techniquesthoughthis example still serves practical purposeeven todaychanges made to shell variables by the code linked into python process are not picked up when you index os environ in python code that isonce your program startsos environ reflects only subsequent changes made by python code in the process moreoveralthough python now has both putenv and getenv call in its os moduletheir integration seems incomplete changes to os environ call os putenvbut direct calls to os putenv do not update os environso the two can become out of sync and os getenv today simply translates to an os environ fetchand hence will not pick up environment changes made in the process outside of python code after startup time this may rarelyif everbe an issue for youbut this extension module is not completely without purposeto truly interface environment variables with linked-in codewe need to call the library routines directly (at least until python changes this model again!the cenviron file in example - creates python module called cenviron that does bit more than the prior examples--it exports two functionssets some exception descriptions explicitlyand makes reference count call for the python none object (it' not created anewso we need to add reference before passing it to pythonas beforewrapping environment calls |
6,061 | in example - builds the source code for dynamic binding on imports example - pp \integrate\extend\cenviron\makefile cenviron #################################################################compile cenviron into cenviron dll-- shareable object file on cygwinwhich is loaded dynamically when first imported #################################################################pylib /usr/local/bin pyinc /usr/local/include/python cenviron dllcenviron gcc cenviron - - $(pyinc-shared clean- $(pylib-lpython - $rm - pyc cenviron dll to buildtype make - makefile cenviron at your shell to runmake sure the resulting dll file is in directory on python' module path (the current working directory works too)/pp /integrate/extend/cenvironpython import cenviron cenviron getenv('user'like os environ[keybut refetched 'markcenviron putenv('user''gilligan'like os environ[key]=value cenviron getenv('user' sees the changes too 'gilliganas beforecenviron is bona fide python module object after it is importedwith all the usual attached informationand errors are raised and reported correctly on errorsdir(cenviron['__doc__''__file__''__name__''__packge__''getenv''putenv'cenviron __file__ 'cenviron dllcenviron __name__ 'cenvironcenviron getenv cenviron cenviron getenv('home''/home/markcenviron getenv('nonesuch'systemerrorerror calling getenv python/ integration |
6,062 | some of these calls are made by linked-in codenot by pythoni changed user in the shell prior to this session with an export command)/pp /integrate/extend/cenvironpython import os os environ['user'initialized from the shell 'skipperfrom cenviron import getenvputenv direct library call access getenv('user''skipperputenv('user''gilligan'changes for but not python getenv('user''gilliganos environ['user'oops--does not fetch values again 'skipperos getenv('user'ditto 'skipperadding wrapper classes to flat libraries as isthe extension module exports function-based interfacebut it' easy to wrap its functions in python code that makes the interface look any way you like for instanceexample - makes the functions accessible by dictionary indexing and integrates with the os environ object--it guarantees that the object will stay in sync with fetches and changes made by calling our extension functions example - pp \integrate\extend\cenviron\envmap py import os from cenviron import getenvputenv class envmappingdef __setitem__(selfkeyvalue)os environ[keyvalue putenv(keyvaluedef __getitem__(selfkey)value getenv(keyos environ[keyvalue return value env envmapping(get module' methods wrap in python class on writesenv[key]=value put in os environ too on readsenv[keyintegrity check make one instance to use this moduleclients may import its env object using env['var'dictionary syntax to refer to environment variables example - goes step further and exports the functions as qualified attribute names rather than as calls or keys--variables are referenced with env var attribute syntax wrapping environment calls |
6,063 | import os from cenviron import getenvputenv class envwrapperdef __setattr__(selfnamevalue)os environ[namevalue putenv(namevaluedef __getattr__(selfname)value getenv(nameos environ[namevalue return value env envwrapper(get module' methods wrap in python class on writesenv name=value put in os environ too on readsenv name integrity check make one instance the following shows our python wrappers running atop our extension module' functions to access environment variables the main point to notice here is that you can graft many different sorts of interface models on top of extension functions by providing python wrappers in addition to extensionsfrom envmap import env env['user''skipperenv['user''professorenv['user''professorfrom envattr import env env user 'professorenv user 'gilliganenv user 'gilliganwrapping environment calls with swig you can manually code extension modules like we just didbut you don' necessarily have to because this example really just wraps functions that already exist in standard librariesthe entire cenviron code file in example - can be replaced with simple swig input file that looks like example - example - pp \integrate\extend\swig\environ\environ /**************************************************************swig module description fileto generate all python wrapper code for lib getenv/putenv calls"swig -python environ ***************************************************************%module environ extern char getenv(const char *varname)extern int putenv(char *assignment) python/ integration |
6,064 | its output as beforesimply add swig step to your makefile and compile its output file into shareable object for dynamic linkingand you're in business example - is cygwin makefile that does the job example - pp \integrate\extend\swig\environ\makefile environ-swig build environ extension from swig generated code pylib /usr/local/bin pyinc /usr/local/include/python swig /cygdrive/ /temp/swigwin-/swig _environ dllenviron_wrap gcc environ_wrap - - $(pyinc- $(pylib-lpython -shared - $environ_wrap cenviron $(swig-python environ cleanrm - dll pyc core environ_wrap environ py when run on environ iswig generates two files and two modules--environ py (the python interface module we importand environ_wrap (the lower-level glue code module file we compile into _environ dll to be imported by the pybecause the functions being wrapped here live in standard linked-in librariesthere is nothing to combine with the generated codethis makefile simply runs swig and compiles the wrapper file into extension moduleready to be imported/pp /integrate/extend/swig/environmake - makefile environ-swig /cygdrive/ /temp/swigwin-/swig -python environ gcc environ_wrap - - /usr/local/include/python - /usr/local/bin -lpython -shared - _environ dll and now you're really done the resulting extension module is linked when importedand it' used as before (except that swig handled all the gory bits)/pp /integrate/extend/swig/environls _environ dll environ environ py environ_wrap makefile environ-swig /pp /integrate/extend/swig/environpython import environ environ getenv('user''gilliganenviron __name__environ __file__environ ('environ''environ py'dir(environ'_environ''getenv''putenvwrapping environment calls |
6,065 | turns out there' good causethe library' putenv wants string of the form "user=gilliganto be passedwhich becomes part of the environment in codethis means we must create new piece of memory to pass inwe used malloc in example - to satisfy this constraint howeverthere' no simple and direct way to guarantee this on the python side of the fence in prior python releaseit was apparently sufficient to hold on to the string passed to putenv in temporary python variablebut this no longer works with python and/or swig fix may require either custom function or swig' typemaps which allow its handling of data translations to be customized in the interest of spacewe'll leave addressing this as suggested exercisesee swig for details wrapping +classes with swig so far in this we've been dealing with extension modules--flat function libraries to implement multiple-instance objects in cyou need to code extension typenot module like python classesc types generate multiple-instance objects and can overload ( intercept and implementpython expression operators and type operations types can also support subclassing just like python classeslargely because the type/class distinction has largely evaporated in python you can see what types look like in python' own source library treelook for the objects directory there the code required for type can be large--it defines instance creationnamed methodsoperator implementationsan iterator typeand so onand links all these together with tables--but is largely boilerplate code that is structurally the same for most types you can code new object types in manually like thisand in some applicationsthis approach may make sense but you don' necessarily have to--because swig knows how to generate glue code for +classesyou can instead automatically generate all the extension and wrapper class code required to integrate such an objectsimply by running swig over an appropriate class declaration the wrapped +class provides multiple-instance datatype much like the extension typebut it can be substantially simpler for you to code because swig handles language integration details here' how--given +class declaration and special command-line settingsswig generates the followinga ++-coded python extension module with accessor functions that interface with the +class' methods and members python-coded module with wrapper class (called "shadowor "proxyclass in swig-speakthat interfaces with the +class accessor functions module python/ integration |
6,066 | would be used only from +thensimply run swig in your makefile to scan the +class declaration and compile and link its output the end result is that by importing the shadow class in your python scriptsyou can utilize +classes as though they were really coded in python not only can python programs make and use instances of the +classthey can also customize it by subclassing the generated shadow class simple +extension class to see how this workswe need +class to illustratelet' code one to be used in python scripts you have to understand +to make sense of this sectionof courseand swig supports advanced +tools (including templates and overloaded functions and operators)but 'll keep this example simple for illustration the following +files define number class with four methods (addsubsquareand display) data member (data)and constructor and destructor example - shows the header file example - pp \integrate\extend\swig\shadow\number class number publicnumber(int start)~number()void add(int value)void sub(int value)int square()void display()int data}/constructor /destructor /update data member /return value /print data member example - is the +class' implementation filemost methods print message when called to trace class operations notice how this uses printf instead of ++' coutthis once resolved an output overlap issue when mixing +cout with python standard output streams on cygwin it' probably moot point today--because python ' output system and buffering might mix with ++' arbitrarilyc+should generally flush the output stream (with fflush(stdoutor cout<<flushif it prints intermixed text that doesn' end in newline obscure but true when disparate language systems are mixed example - pp \integrate\extend\swig\shadow\number cxx ///////////////////////////////////////////////////////////////implement +classto be used from python code or not/caveatcout and print usually both workbut ran into / ++/py output overlap issue on cygwin that prompted printf //////////////////////////////////////////////////////////////#include "number #include "stdio /versus #include "iostream hwrapping +classes with swig |
6,067 | data startprintf("number% \ "data)/python print goes to stdout /orcout <"number<data <endlnumber::~number(printf("~number% \ "data)void number::add(int valuedata +valueprintf("add % \ "value)void number::sub(int valuedata -valueprintf("sub % \ "value)int number::square(return data data/if print labelfflush(stdoutor cout <flush void number::display(printf("number=% \ "data)so that you can compare languagesthe following is how this class is used in +program example - makes number objectcalls its methodsand fetches and sets its data attribute directly ( +distinguishes between "membersand "methods,while they're usually both called "attributesin pythonexample - pp \integrate\extend\swig\shadow\main cxx #include "iostream #include "number hmain(number *numint resvalnum new number( )num->add( )num->display()num->sub( )num->display()/make +class instance /call its methods res num->square()cout <"square<res <endl/method return value num->data val num->datacout <"data<val <endl/set +data member /fetch +data member python/ integration |
6,068 | num->display()cout <num <endldelete num/print raw instance ptr /run destructor you can use the +command-line +compiler program to compile and run this code on cygwin (it' the same on linuxif you don' use similar systemyou'll have to extrapolatethere are far too many +compiler differences to list here type the compile command directly or use the cxxtest target in this example directory' makefile shown aheadand then run the purely +program created/pp /integrate/extend/swig/shadowmake - makefile number-swig cxxtest +main cxx number cxx -wno-deprecated /pp /integrate/extend/swig/shadow/ exe number add number= sub number= square data data+ number= xe ~number wrapping the +class with swig but enough ++let' get back to python to use the +number class of the preceding section in python scriptsyou need to code or generate glue logic layer between the two languagesjust as in prior extension examples to generate that layer automaticallywrite swig input file like the one shown in example - example - pp \integrate\extend\swig\shadow\number /*******************************************************swig module description file for wrapping +class generate by running "swig - +-python number ithe +module is generated in file number_wrap cxxmodule 'numberrefers to the number py shadow class ********************************************************%module number %#include "number %%include number wrapping +classes with swig |
6,069 | generate two different python modules againnumber_wrap cxx +extension module with class accessor functions number py python shadow class module that wraps accessor functions the former must be compiled into binary library the latter imports and uses the former' compiled form and is the file that python scripts ultimately import as for simple functionsswig achieves the integration with combination of python and +code after running swigthe cygwin makefile shown in example - combines the generated number_wrap cxx +wrapper code module with the +class implementation file to create _number dll-- dynamically loaded extension module that must be in directory on your python module search path when imported from python scriptalong with the generated number py (all files are in the same current working directory hereas beforethe compiled extension module must be named with leading underscore in swig today_number dllfollowing python conventionrather than the other formats used by earlier releases the shadow class module number py internally imports _number dll be sure to use - +command-line argument for swigan older -shadow argument is no longer needed to create the wrapper class in addition to the lower-level functional interface moduleas this is enabled by default example - pp \integrate\extend\swig\shadow\makefile number-swig ##########################################################################use swig to integrate the number +class for use in python programs updatename "_number dllmattersbecause shadow class imports _number updatethe "-shadowswig command line arg is deprecated (on by defaultupdateswig no longer creates doc file to rm here (ancient history##########################################################################pylib /usr/local/bin pyinc /usr/local/include/python swig /cygdrive/ /temp/swigwin-/swig all_number dll number py wrapper real class _number dllnumber_wrap number +-shared number_wrap number - $(pylib-lpython - $generated class wrapper module(snumber_wrap onumber_wrap cxx number +number_wrap cxx - - - $(pyinc python/ integration |
6,070 | $(swig- +-python number number pynumber $(swig- +-python number wrapped +class code number onumber cxx number +number cxx - - -wno-deprecated non python test cxxtestg+main cxx number cxx -wno-deprecated cleanforcerm - pyc dll core exe rm - pyc dll core exe number_wrap cxx number py as usualrun this makefile to generate and compile the necessary glue code into an extension module that can be imported by python programs/pp /integrate/extend/swig/shadowmake - makefile number-swig /cygdrive/ /temp/swigwin-/swig - +-python number +number_wrap cxx - - - /usr/local/include/python +number cxx - - -wno-deprecated +-shared number_wrap number - /usr/local/bin -lpython - _number dll /pp /integrate/extend/swig/shadowls _number dll makefile number-swig number exe number cxx number main cxx number number py number_wrap cxx number_wrap using the +class in python once the glue code is generated and compiledpython scripts can access the +class as though it were coded in python in factit is--the imported number py shadow class which runs on top of the extension module is generated python code example - repeats the main cxx file' class tests herethoughthe +class is being utilized from the python programming language--an arguably amazing featbut the code is remarkably natural on the python side of the fence example - pp \integrate\extend\swig\shadow\main py ""use +class in python code ( +module py shadow classthis script runs the same tests as the main cxx +file ""from number import number imports py +shadow class module num number( num add( make +class object in python call its methods from python wrapping +classes with swig |
6,071 | num sub( num display(num saves the +'thispointer res num square(print('square'resconverted +int return value num data val num data print('data'valprint('data+ 'val set +data membergenerated __setattr__ get +data membergenerated __getattr__ returns normal python integer object num display(print(numdel num runs repr in shadow/proxy class runs +destructor automatically because the +class and its wrappers are automatically loaded when imported by the number py shadow class moduleyou run this script like any other/pp /integrate/extend/swig/shadowpython main py number add number= sub number= square data data+ number= ~number much of this output is coming from the +class' methods and is largely the same as the main cxx results shown in example - (less the instance output format--it' python shadow class instance nowusing the low-level extension module swig implements integrations as ++/python combinationbut you can always use the generated accessor functions module if you want toas in example - this version runs the +extension module directly without the shadow classto demonstrate how the shadow class maps calls back to +example - pp \integrate\extend\swig\shadow\main_low py ""run similar tests to main cxx and main py but use low-level accessor function interface ""from _number import +extension module wrapper num new_number( number_add(num pass +'thispointer explicitly python/ integration |
6,072 | number_sub(num number_display(numprint(number_square(num)use accessor functions in the module number_data_set(num print(number_data_get(num)number_display(numprint(numdelete_number(numthis script generates essentially the same output as main pybut it' been slightly simplifiedand the +class instance is something lower level than the proxy class here/pp /integrate/extend/swig/shadowpython main_low py number add number= sub number= number= aa _p_number ~number subclassing the +class in python using the extension module directly worksbut there is no obvious advantage to moving from the shadow class to functions here by using the shadow classyou get both an object-based interface to +and customizable python object for instancethe python module shown in example - extends the +classadding an extra print call statement to the +add method and defining brand-new mul method because the shadow class is pure pythonthis works naturally example - pp \integrate\extend\swig\shadow\main_subclass py "sublass +class in python (generated shadow class)from number import number import shadow class class mynumber(number)def add(selfother)print('in python add 'number add(selfotherdef mul(selfother)print('in python mul 'self data self data other num mynumber( num add( num display(num sub( num display(extend method add new method same tests as main cxxmain py using python subclass of shadow class add(is specialized in python wrapping +classes with swig |
6,073 | num data print(num datanum display(num mul( num display(print(numdel num mul(is implemented in python repr from shadow superclass now we get extra messages out of add callsand mul changes the +class' data member automatically when it assigns self data--the python code extends the +code/pp /integrate/extend/swig/shadowpython main_subclass py number in python add add number= sub number= number= in python mul number= ~number in other wordsswig makes it easy to use +class libraries as base classes in your python scripts among other thingsthis allows us to leverage existing +class libraries in python scripts and optimize by coding parts of class hierarchies in +when needed we can do much the same with extension types today since types are classes (and vice versa)but wrapping +classes with swig is often much simpler exploring the wrappers interactively as usualyou can import the +class interactively to experiment with it some more-besides demonstrating few more salient properties herethis technique allows us to test wrapped +classes at the python interactive prompt/pp /integrate/extend/swig/shadowpython import _number _number __file__ the +class plus generated glue module '_number dllimport number the generated python shadow class module number __file__ 'number pyx number number( number number number( number python/ integration make +class instance in python make another +object |
6,074 | >> display(number= add( dataadd display(number= call +method (like + ->display()fetch +data membercall +method data data data display(number= set +data member records the +this pointer square( square(ttype( ( method with return value type is class in python naturallythis example uses small +class to underscore the basicsbut even at this levelthe seamlessness of the python-to- +integration we get from swig is astonishing python code uses +members and methods as though they are python code moreoverthis integration transparency still applies once we step up to more realistic +class libraries so what' the catchnothing muchreallybut if you start using swig in earnestthe biggest downside may be that swig cannot handle every feature of +today if your classes use some esoteric +tools (and there are many)you may need to handcode simplified class type declarations for swig instead of running swig over the original class header files swig development is ongoingso you should consult the swig manuals and website for more details on these and other topics in return for any such trade-offsthoughswig can completely obviate the need to code glue layers to access and +libraries from python scripts if you have ever coded such layers by hand in the pastyou already know that this can be very big win if you do go the handcoded routethoughconsult python' standard extension manuals for more details on both api calls used in this as well as additional extension tools we don' have space to cover in this text extensions can run the gamut from short swig input files to code that is staunchly wedded to the internals of the python interpreteras rule of thumbthe former survives the ravages of time much better than the latter other extending tools in closing the extending topici should mention that there are alternatives to swigmany of which have loyal user base of their own this section briefly introduces some of the more popular tools in this domain todayas usualsearch the web for more other extending tools |
6,075 | tools installed separatelythough python and later incorporates the ctypes extension as standard library module sip just as sip is smaller swig in the drinking worldso too is the sip system lighter alternative to swig in the python world (in factit was named on purpose for the jokeaccording to its web pagesip makes it easy to create python bindings for and +libraries originally developed to create the pyqt python bindings for the qt toolkitit can be used to create bindings for any or +library sip includes code generator and python support module much like swigthe code generator processes set of specification files and generates or +codewhich is compiled to create the bindings extension module the sip python module provides support functions to the automatically generated code unlike swigsip is specifically designed just for bringing together python and / +swig also generates wrappers for many other scripting languagesand so is viewed by some as more complex project ctypes the ctypes system is foreign function interface (ffimodule for python it allows python scripts to access and call compiled functions in binary library file directly and dynamicallyby writing dispatch code in python itselfinstead of generating or writing the integration wrapper code we've studied in this that islibrary glue code is written in pure python instead of the main advantage is that you don' need code or build system to access functions from python script the disadvantage is potential speed loss on dispatchthough this depends upon the alternative measured according to its documentationctypes allows python to call functions exposed from dlls and shared libraries and has facilities to createaccessand manipulate complex datatypes in python it is also possible to implement callback functions in pure pythonand an experimental ctypes code generator feature allows automatic creation of library wrappers from header files ctypes works on windowsmac os xlinuxsolarisfreebsdand openbsd it may run on additional systemsprovided that the libffi package it employs is supported for windowsctypes contains ctypes com packagewhich allows python code to call and implement custom com interfaces see python' library manuals for more on the ctypes functionality included in the standard library boost python the boost python system is +library that enables seamless interoperability between +and the python programming language through an idl-like model using itdevelopers generally write small amount of +wrapper code to create shared library for use in python scripts boost python handles referencescallbackstype mappingsand cleanup tasks because it is designed to wrap +interfaces nonintrusivelyc+code need not be changed to be wrapped like other python/ integration |
6,076 | developing new extensions from scratch writing interface code for large libraries can be more involved than the code generation approaches of swig and sipbut it' easier than manually wrapping libraries and may afford greater control than fully automated wrapping tool in additionthe py+and older pyste systems provide boost python code generatorsin which users specify classes and functions to be exported using simple interface file both use gcc-xml to parse all the headers and extract the necessary information to generate +code cython (and pyrexcythona successor to the pyrex systemis language specifically for writing python extension modules it lets you write files that mix python code and datatypes as you wishand compiles the combination into extension for python in principledevelopers need not deal with the python/ api at allbecause cython takes care of things such as error-checking and reference counts automatically technicallycython is distinct language that is python-likewith extensions for mixing in datatype declarations and function calls howeveralmost any python code is also valid cython code the cython compiler converts python code into codewhich makes calls to the python/ api in this aspectcython is similar to the now much older python conversion project by combining python and codecython offers different approach than the generation or coding of integration code in other systems cxxweaveand more the cxx system is roughly +version of python' usual apiwhich handles reference countersexception translationand much of the type checking and cleanup inherent in +extensions as suchcxx lets you focus on the application-specific parts of your code cxx also exposes parts of the +standard template library containers to be compatible with python sequences the weave package allows the inclusion of / +in python code it' part of the scipy package ( page at which we don' have space to mention here other languagesjavac#fortranobjective-cand others although we're focused on and +in this you'll also find direct support for mixing python with other programming languages in the open source world this includes languages that are compiled to binary form like cas well as some that are not for exampleby providing full byte code compilersthe jython and ironpython systems allow code written in python to interface with java and #net components in largely seamless fashion alternativelythe jpype and python for net projects support java and #net integration for normal cpython (the standard other extending tools |
6,077 | compilers moreoverthe py and pyfort systems provide integration with fortran codeand other tools provide access to languages such as delphi and objective- among thesethe pyobjc project aims to provide bridge between python and objective-cthis supports writing cocoa gui applications on mac os in python search the web for details on other language integration tools also look for wiki page currently at because many of these systems support bidirectional control flows--both extending and embedding--we'll return to this category at the end of this in the context of integration at large firstthoughwe need to shift our perspective degrees to explore the other mode of python/ integrationembedding mixing python and +python' standard implementation is currently coded in cso all the normal rules about mixing programs with +programs apply to the python interpreter in factthere is nothing special about python in this contextbut here are few pointers when embedding python in +programthere are no special rules to follow simply link in the python library and call its functions from +python' header files automatically wrap themselves in extern "cdeclarations to suppress +name mangling hencethe python library looks like any other component to ++there is no need to recompile python itself with +compiler when extending python with +componentspython header files are still +friendlyso python api calls in +extensions work like any other ++-to- call but be sure to wrap the parts of your extension code made visible to python with extern "cdeclarations so that they can be called by python' code for exampleto wrap +classswig generates +extension module that declares its initialization function this way embedding python in coverview so far in this we've explored only half of the python/ integration picturecalling services from python this mode is perhaps the most commonly deployedit allows programmers to speed up operations by moving them to and to utilize external libraries by wrapping them in extension modules and types but the inverse can be just as usefulcalling python from by delegating selected components of an application to embedded python codewe can open them up to onsite changes without having to ship or rebuild system' full code base this section tells this other half of the python/ integration tale it introduces the python interfaces that make it possible for programs written in -compatible python/ integration |
6,078 | control language (what some call "macrolanguagealthough embedding is mostly presented in isolation herekeep in mind that python' integration support is best viewed as whole system' structure usually determines an appropriate integration approachc extensionsembedded code callsor both to wrap upthis concludes by discussing handful of alternative integration platforms such as jython and ironpythonwhich offer broad integration possibilities the embedding api the first thing you should know about python' embedded-call api is that it is less structured than the extension interfaces embedding python in may require bit more creativity on your part than extendingyou must pick tools from general collection of calls to implement the python integration instead of coding to boilerplate structure the upside of this loose structure is that programs can combine embedding calls and strategies to build up arbitrary integration architectures the lack of more rigid model for embedding is largely the result of less clear-cut goal when extending pythonthere is distinct separation for python and responsibilities and clear structure for the integration modules and types are required to fit the python module/type model by conforming to standard extension structures this makes the integration seamless for python clientsc extensions look like python objects and handle most of the work it also supports automation tools such as swig but when python is embeddedthe structure isn' as obviousbecause is the enclosing levelthere is no clear way to know what model the embedded python code should fit may want to run objects fetched from modulesstrings fetched from files or parsed out of documentsand so on instead of deciding what can and cannot dopython provides collection of general embedding interface toolswhich you use and structure according to your embedding goals most of these tools correspond to tools available to python programs table - lists some of the more common api calls used for embeddingas well as their python equivalents in generalif you can figure out how to accomplish your embedding goals in pure python codeyou can probably find api tools that achieve the same results table - common api functions api call python equivalent pyimport_importmodule import module__import__ pyimport_getmoduledict sys modules pymodule_getdict module __dict__ pydict_getitemstring dict[keypydict_setitemstring dict[key]=val pydict_new dict {embedding python in coverview |
6,079 | python equivalent pyobject_getattrstring getattr(objattrpyobject_setattrstring setattr(objattrvalpyobject_callobject funcobj(*argstuplepyeval_callobject funcobj(*argstuplepyrun_string eval(exprstr)exec(stmtstrpyrun_file exec(open(filename(read()because embedding relies on api call selectionbecoming familiar with the python api is fundamental to the embedding task this presents handful of representative embedding examples and discusses common api callsbut it does not provide comprehensive list of all tools in the api once you've mastered the examples hereyou'll probably need to consult python' integration manuals for more details on available calls in this domain as mentioned previouslypython offers two standard manuals for / +integration programmersextending and embeddingan integration tutorialand python/ apithe python runtime library reference you can find the most recent releases of these manuals at possibly installed on your computer alongside python itself beyond this these manuals are likely to be your best resource for up-to-date and complete python api tool information what is embedded codebefore we jump into detailslet' get handle on some of the core ideas in the embedding domain when this book speaks of "embeddedpython codeit simply means any python program structure that can be executed from with direct in-process function call interface generally speakingembedded python code can take variety of formscode strings programs can represent python programs as character strings and run them as either expressions or statements (much like using the eval and exec built-in functions in pythoncallable objects programs can load or reference python callable objects such as functionsmethodsand classesand call them with argument list objects (much like func(*pargs*kargspython syntaxcode files programs can execute entire python program files by importing modules and running script files through the api or general system calls ( popen python/ integration |
6,080 | program the actual python code run from can come from wide variety of sourcescode strings might be loaded from filesobtained from an interactive user at console or guifetched from persistent databases and shelvesparsed out of html or xml filesread over socketsbuilt or hardcoded in programpassed to extension functions from python registration codeand so on callable objects might be fetched from python modulesreturned from other python api callspassed to extension functions from python registration codeand so on code files simply exist as filesmodulesand executable scripts in the filesystem registration is technique commonly used in callback scenarios that we will explore in more detail later in this but especially for strings of codethere are as many possible sources as there are for character strings in general for examplec programs can construct arbitrary python code dynamically by building and running strings finallyonce you have some python code to runyou need way to communicate with itthe python code may need to use inputs passed in from the layer and may want to generate outputs to communicate results back to in factembedding generally becomes interesting only when the embedded code has access to the enclosing layer usuallythe form of the embedded code suggests its communication mediacode strings that are python expressions return an expression result as their output in additionboth inputs and outputs can take the form of global variables in the namespace in which code string is runc may set variables to serve as inputrun python codeand fetch variables as the code' result inputs and outputs can also be passed with exported extension function calls--python code may use module or type interfaces that we met earlier in this to get or set variables in the enclosing layer communications schemes are often combinedfor instancec may preassign global names to objects that export both state and interface functions for use in the embedded python code callable objects may accept inputs as function arguments and produce results as function return values passed-in mutable arguments ( listsdictionariesclass instancescan be used as both input and output for the embedded code--changes made in python are retained in objects held by objects can also make use of the global variable and extension functions interface techniques described for strings to communicate with for concrete exampleconsider the discussion of server-side templating languages in the internet part of this book such systems usually fetch python code embedded in an html web page fileassign global variables in namespace to objects that give access to the web browser' environmentand run the python code in the namespace where the objects were assigned worked on project where we did something similarbut python code was embedded in xml documentsand objects that were preassigned to globals in the code' namespace represented widgets in gui at the bottomit was simply python code embedded in and run by code embedding python in coverview |
6,081 | when run as separate programsfiles can also employ inter-process communication (ipctechniques naturallyall embedded code forms can also communicate with using general systemlevel toolsfilessocketspipesand so on these techniques are generally less direct and slowerthough herewe are still interested in in-process function call integration basic embedding techniques as you can probably tell from the preceding overviewthere is much flexibility in the embedding domain to illustrate common embedding techniques in actionthis section presents handful of short programs that run python code in one form or another most of these examples will make use of the simple python module file shown in example - example - pp \integrate\embed\basics\usermod py ""############################################################ code runs python code in this module in embedded mode such file can be changed without changing the layer this is just standard python code ( handles conversionsmust be on the python module search path if imported by can also run code in standard library modules like string ############################################################""message 'the meaning of life def transform(input)input input replace('life''python'return input upper(if you know any python at allyou probably know that this file defines string and functionthe function returns whatever it is passed with string substitution and uppercase conversions applied it' easy to use from python/pp /integrate/embed/basicspython import usermod usermod message 'the meaning of life usermod transform(usermod message'the meaning of python import module fetch string call function with little python api wizardryit' not much more difficult to use this module the same way in python/ integration |
6,082 | perhaps the simplest way to run python code from is by calling the pyrun_simple string api function with itc programs can execute python programs represented as character string arrays this call is also very limitedall code runs in the same namespace (the module __main__)the code strings must be python statements (not expressions)and there is no direct way to communicate inputs or outputs with the python code run stillit' simple place to start moreoverwhen augmented with an imported extension module that the embedded python code can use to communicate with the enclosing layerthis technique can satisfy many embedding goals to demonstrate the basicsthe program in example - runs python code to accomplish the same results as the python interactive session listed in the prior section example - pp \integrate\embed\basics\embed-simple /******************************************************simple code stringsc acts like the interactive promptcode runs in __main__no output sent to *******************************************************#include /standard api def *main(printf("embed-simple\ ")py_initialize()pyrun_simplestring("import usermod")pyrun_simplestring("print(usermod message)")pyrun_simplestring(" usermod message")pyrun_simplestring("print(usermod transform( ))")py_finalize()/load py file */on python path */compile and run *the first thing you should notice here is that when python is embeddedc programs always call py_initialize to initialize linked-in python libraries before using any other api functions and normally call py_finalize to shut the interpreter down the rest of this code is straightforward-- submits hardcoded strings to python that are roughly what we typed interactively in factwe could concatenate all the python code strings here with \ characters betweenand submit it once as single string internallypyrun_simplestring invokes the python compiler and interpreter to run the strings sent from cas usualthe python compiler is always available in systems that contain python compiling and running to build standalone executable from this source fileyou need to link its compiled form with the python library file in this "libraryusually means the binary basic embedding techniques |
6,083 | standard library todayeverything in python that you need in is compiled into single python library file when the interpreter is built ( libpython dll on cygwinthe program' main function comes from your codeand depending on your platform and the extensions installed in your pythonyou may also need to link any external libraries referenced by the python library assuming no extra extension libraries are neededexample - is minimal makefile for building the program in example - under cygwin on windows againmakefile details vary per platformbut see python manuals for hints this makefile uses the python include-files path to find python in the compile step and adds the python library file to the final link step to make api calls available to the program example - pp \integrate\embed\basics\makefile cygwin makefile that builds executable that embeds pythonassuming no external module libs must be linked inuses python header fileslinks in the python lib fileboth may be in other dirs ( /usrin your installpylib /usr/local/bin pyinc /usr/local/include/python embed-simpleembed-simple gcc embed-simple - $(pylib-lpython - - embed-simple embed-simple oembed-simple gcc embed-simple - - - $(pyincto build program with this filelaunch make on it as usual (as beforemake sure indentation in rules is tabs in your copy of this makefile)/pp /integrate/embed/basicsmake - makefile gcc embed-simple - - - /usr/local/include/python gcc embed-simple - /usr/local/bin -lpython - - embed-simple things may not be quite this simple in practicethoughat least not without some coaxing the makefile in example - is the one actually used to build all of this section' programs on cygwin example - pp \integrate\embed\basics\makefile basics cygwin makefile to build all basic embedding examples at once pylib /usr/local/bin pyinc /usr/local/include/python basics embed-simple exe embed-string exe embed-object exe embed-dict exe python/ integration |
6,084 | all$(basicsembedexeembedo gcc embed$ - $(pylib-lpython - - $embedoembedc gcc embed$ - - - $(pyinccleanrm - pyc $(basicscore on some platformsyou may need to also link in other libraries because the python library file used may have been built with external dependencies enabled and required in factyou may have to link in arbitrarily many more externals for your python libraryand franklychasing down all the linker dependencies can be tedious required libraries may vary per platform and python installso there isn' lot of advice can offer to make this process simple (this is cafter allthe standard development techniques will apply one hint hereif you're going to do much embedding work and you run into external dependency issueson some platforms you might want to build python on your machine from its source with all unnecessary extensions disabled in its build configuration files (see the python source package for detailsthis produces python library with minimal external requirementswhich may links more easily once you've gotten the makefile to workrun it to build all of this section' programs at once with python libraries linked in/pp /integrate/embed/basicsmake - makefile basics clean rm - pyc embed-simple exe embed-string exe embed-object exe embed-dict exe embed-bytecode exe core /pp /integrate/embed/basicsmake - makefile basics gcc embed-simple - - - /usr/local/include/python gcc embed-simple - /usr/local/bin -lpython - - embed-simple exe gcc embed-string - - - /usr/local/include/python gcc embed-string - /usr/local/bin -lpython - - embed-string exe gcc embed-object - - - /usr/local/include/python gcc embed-object - /usr/local/bin -lpython - - embed-object exe gcc embed-dict - - - /usr/local/include/python gcc embed-dict - /usr/local/bin -lpython - - embed-dict exe gcc embed-bytecode - - - /usr/local/include/python gcc embed-bytecode - /usr/local/bin -lpython - - embed-bytecode exe rm embed-dict embed-object embed-simple embed-bytecode embed-string after building with either makefileyou can run the resulting program as usual/pp /integrate/embed/basics/embed-simple embed-simple the meaning of life the meaning of python basic embedding techniques |
6,085 | naturallystrings of python code run by probably would not be hardcoded in program file like this they might instead be loaded from text file or guiextracted from html or xml filesfetched from persistent database or socketand so on with such external sourcesthe python code strings that are run from could be changed arbitrarily without having to recompile the program that runs them they may even be changed on siteand by end users of system to make the most of code stringsthoughwe need to move on to more flexible api tools pragmatic detailsunder python and cygwin on windowsi had to first set my pythonpath to include the current directory in order to run the embedding exampleswith the shell command export python pathi also had to use the shell command /embed-simple to execute the program because was also not on my system path setting and isn' initially when you install cygwin your mileage may varybut if you have troubletry running the embedded python commands import sys and print sys path from to see what python' path looks likeand take look at the python/ api manual for more on path configuration for embedded applications running code strings with results and namespaces example - uses the following api calls to run code strings that return expression results back to cpy_initialize initializes linked-in python libraries as before pyimport_importmodule imports python module and returns pointer to it pymodule_getdict fetches module' attribute dictionary object pyrun_string runs string of code in explicit namespaces pyobject_setattrstring assigns an object attribute by namestring pyarg_parse converts python return value object to form the import calls are used to fetch the namespace of the usermod module listed in example - so that code strings can be run there directly and will have access to names defined in that module without qualifications py_import_importmodule is like python import statementbut the imported module object is returned to cit is not assigned python/ integration |
6,086 | __import__ built-in function the pyrun_string call is the one that actually runs code herethough it takes code stringa parser mode flagand dictionary object pointers to serve as the global and local namespaces for running the code string the mode flag can be py_eval_input to run an expression or py_file_input to run statementwhen running an expressionthe result of evaluating the expression is returned from this call (it comes back as pyobjectobject pointerthe two namespace dictionary pointer arguments allow you to distinguish global and local scopesbut they are typically passed the same dictionary such that code runs in single namespace example - pp \integrate\embed\basics\embed-string /code-strings with results and namespaces *#include main(char *cstrpyobject *pstr*pmod*pdictprintf("embed-string\ ")py_initialize()/get usermod message *pmod pyimport_importmodule("usermod")pdict pymodule_getdict(pmod)pstr pyrun_string("message"py_eval_inputpdictpdict)/convert to *pyarg_parse(pstr" "&cstr)printf("% \ "cstr)/assign usermod *pyobject_setattrstring(pmod" "pstr)/print usermod transform( *(voidpyrun_string("print(transform( ))"py_file_inputpdictpdict)py_decref(pmod)py_decref(pstr)py_finalize()when compiled and runthis file produces the same result as its predecessor/pp /integrate/embed/basics/embed-string embed-string the meaning of life the meaning of python howeververy different work goes into producing this output this timec fetchesconvertsand prints the value of the python module' message attribute directly by basic embedding techniques |
6,087 | namespace to serve as input for python print statement string because the string execution call in this version lets you specify namespacesyou can better partition the embedded code your system runs--each grouping can have distinct namespace to avoid overwriting other groupsvariables and because this call returns resultyou can better communicate with the embedded codeexpression results are outputsand assignments to globals in the namespace in which code runs can serve as inputs before we move oni need to explain three coding issues here firstthis program also decrements the reference count on objects passed to it from pythonusing the py_decref call described in python' api manuals these calls are not strictly needed here (the objectsspace is reclaimed when the programs exits anyhow)but they demonstrate how embedding interfaces must manage reference counts when python passes object ownership to if this was function called from larger systemfor instanceyou would generally want to decrement the count to allow python to reclaim the objects secondin realistic programyou should generally test the return values of all the api calls in this program immediately to detect errors ( import failureerror tests are omitted in this section' example to keep the code simplebut they should be included in your programs to make them more robust and thirdthere is related function that lets you run entire files of codebut it is not demonstrated in this pyrun_file because you can always load file' text and run it as single code string with pyrun_stringthe pyrun_file call' main advantage is to avoid allocating memory for file content in such multiline code stringsthe \ character terminates lines and indentation group blocks as usual calling python objects the last two sections dealt with running strings of codebut it' easy for programs to deal in terms of python objectstoo example - accomplishes the same task as examples - and - but it uses other api tools to interact with objects in the python module directlypyimport_importmodule imports the module from as before pyobject_getattrstring fetches an object' attribute value by name pyeval_callobject calls python function (or class or methodpyarg_parse converts python objects to values python/ integration |
6,088 | converts values to python objects we used both of the data conversion functions earlier in this in extension modules the pyeval_callobject call in this version of the example is the key point hereit runs the imported function with tuple of argumentsmuch like the python func(*argscall syntax the python function' return value comes back to as pyobject* generic python object pointer example - pp \integrate\embed\basics\embed-object /fetch and call objects in modules *#include main(char *cstrpyobject *pstr*pmod*pfunc*pargsprintf("embed-object\ ")py_initialize()/get usermod message *pmod pyimport_importmodule("usermod")pstr pyobject_getattrstring(pmod"message")/convert string to *pyarg_parse(pstr" "&cstr)printf("% \ "cstr)py_decref(pstr)/call usermod transform(usermod message*pfunc pyobject_getattrstring(pmod"transform")pargs py_buildvalue("( )"cstr)pstr pyeval_callobject(pfuncpargs)pyarg_parse(pstr" "&cstr)printf("% \ "cstr)/free owned objects *py_decref(pmod)py_decref(pstr)py_decref(pfunc)/not really needed in main(*py_decref(pargs)/since all memory goes away *py_finalize()when compiled and runthe result is the same again/pp /integrate/embed/basics/embed-object embed-object the meaning of life the meaning of python howeverthis output is generated by this time--firstby fetching the python module' message attribute valueand then by fetching and calling the module' transform basic embedding techniques |
6,089 | transform function is function argument herenot preset global variable notice that message is fetched as module attribute this timeinstead of by running its name as code stringas this showsthere is often more than one way to accomplish the same goals with different api calls running functions in modules like this is simple way to structure embeddingcode in the module file can be changed arbitrarily without having to recompile the program that runs it it also provides direct communication modelinputs and outputs to python code can take the form of function arguments and return values running strings in dictionaries when we used pyrun_string earlier to run expressions with resultscode was executed in the namespace of an existing python module sometimesthoughit' more convenient to create brand-new namespace for running code strings that is independent of any existing module files the file in example - shows howthe new namespace is created as new python dictionary objectand handful of new api calls are employed in the processpydict_new makes new empty dictionary object pydict_setitemstring assigns to dictionary' key pydict_getitemstring fetches (indexesa dictionary value by key pyrun_string runs code string in namespacesas before pyeval_getbuiltins gets the built-in scope' module the main trick here is the new dictionary inputs and outputs for the embedded code strings are mapped to this dictionary by passing it as the code' namespace dictionaries in the pyrun_string call the net effect is that the program in example - works just like this python coded { [' ' exec(' 'ddexec(' 'ddprint( [' '] but hereeach python operation is replaced by api call python/ integration |
6,090 | /make new dictionary for code string namespace *#include main(int cvalpyobject *pdict*pvalprintf("embed-dict\ ")py_initialize()/make new namespace *pdict pydict_new()pydict_setitemstring(pdict"__builtins__"pyeval_getbuiltins())pydict_setitemstring(pdict" "pylong_fromlong( ))pyrun_string(" "py_file_inputpdictpdict)pyrun_string(" + "py_file_inputpdictpdict)pval pydict_getitemstring(pdict" ")/dict[' ' */run statements */same and */fetch dict[' '*pyarg_parse(pval" "&cval)printf("% \ "cval)py_decref(pdict)py_finalize()/convert to */result= *when compiled and runthis program creates this sort of outputtailored for this use case/pp /integrate/embed/basics/embed-dict embed-dict the output is different this timeit reflects the value of the python variable assigned by the embedded python code strings and fetched by in generalc can fetch module attributes either by calling pyobject_getattrstring with the module or by using pydict_getitemstring to index the module' attribute dictionary (expression strings worktoobut they are less directherethere is no module at allso dictionary indexing is used to access the code' namespace in besides allowing you to partition code string namespaces independent of any python module files on the underlying systemthis scheme provides natural communication mechanism values that are stored in the new dictionary before code is run serve as inputsand names assigned by the embedded code can later be fetched out of the dictionary to serve as code outputs for instancethe variable in the second string run refers to name set to by cx is assigned by the python code and fetched later by code as the printed result basic embedding techniques |
6,091 | for running code are generally required to have __builtins__ link to the built-in scope searched last for name lookupsset with code of this formpydict_setitemstring(pdict"__builtins__"pyeval_getbuiltins())this is esotericand it is normally handled by python internally for modules and builtins like the exec function for raw dictionaries used as namespacesthoughwe are responsible for setting the link manually if we expect to reference built-in names this still holds true in python precompiling strings to bytecode finallywhen you call python function objects from cyou are actually running the already compiled bytecode associated with the object ( function body)normally created when the enclosing module is imported when running stringspython must compile the string before running it because compilation is slow processthis can be substantial overhead if you run code string more than once insteadprecompile the string to bytecode object to be run laterusing the api calls illustrated in example - py_compilestring compiles string of code and returns bytecode object pyeval_evalcode runs compiled bytecode object the first of these takes the mode flag that is normally passed to pyrun_stringas well as second string argument that is used only in error messages the second takes two namespace dictionaries these two api calls are used in example - to compile and execute three strings of python code in turn example - pp \integrate\embed\basics\embed-bytecode /precompile code strings to bytecode objects *#include #include #include main(int ichar *cvalpyobject *pcode *pcode *pcode *presult*pdictchar *codestr *codestr *codestr printf("embed-bytecode\ ")py_initialize()codestr "import usermod\nprint(usermod message)"codestr "usermod transform(usermod message)"codestr "print('% :% (xx * )end=')" python/ integration /statements */expression */use input * |
6,092 | pdict pydict_new()if (pdict =nullreturn - pydict_setitemstring(pdict"__builtins__"pyeval_getbuiltins())/precompile strings of code to bytecode objects *pcode py_compilestring(codestr ""py_file_input)pcode py_compilestring(codestr ""py_eval_input)pcode py_compilestring(codestr ""py_file_input)/run compiled bytecode in namespace dict *if (pcode &pcode &pcode (voidpyeval_evalcode((pycodeobject *)pcode pdictpdict)presult pyeval_evalcode((pycodeobject *)pcode pdictpdict)pyarg_parse(presult" "&cval)printf("% \ "cval)py_decref(presult)/rerun code object repeatedly *for ( < ++pydict_setitemstring(pdict" "pylong_fromlong( ))(voidpyeval_evalcode((pycodeobject *)pcode pdictpdict)printf("\ ")/free referenced objects *py_xdecref(pdict)py_xdecref(pcode )py_xdecref(pcode )py_xdecref(pcode )py_finalize()this program combines variety of techniques that we've already seen the namespace in which the compiled code strings runfor instanceis newly created dictionary (not an existing module object)and inputs for code strings are passed as preset variables in the namespace when built and executedthe first part of the output is similar to previous examples in this sectionbut the last line represents running the same precompiled code string times/pp /integrate/embed/basicsembed-bytecode embed-bytecode the meaning of life the meaning of python : : : : : : : : : : : if your system executes python code strings multiple timesit is major speedup to precompile to bytecode in this fashion this step is not required in other contexts that invoke callable python objects--including the common embedding use case presented in the next section basic embedding techniques |
6,093 | in the embedding examples thus farc has been running and calling python code from standard main program flow of control things are not always so simplethoughin some casesprograms are modeled on an event-driven architecture in which code is executed only in response to some sort of event the event might be an end user clicking button in guithe operating system delivering signalor simply software running an action associated with an entry in table in any event (pun accidental)program code in such an architecture is typically structured as callback handlers--units of code invoked by event-processing dispatch logic it' easy to use embedded python code to implement callback handlers in such systemin factthe event-processing layer can simply use the embedded-call api tools we saw earlier in this to run python handlers the only new trick in this model is how to make the layer know what code should be run for each event handlers must somehow be registered to to associate them with future events in generalthere is wide variety of ways to achieve this code/event association for instancec programs canfetch and call functions by event name from one or more module files fetch and run code strings associated with event names in database extract and run code associated with event tags in html or xml run python code that calls back to to tell it what should be run and so on reallyany place you can associate objects or strings with identifiers is potential callback registration mechanism some of these techniques have advantages all their own for instancecallbacks fetched from module files support dynamic reloading (imp reload works on modules but does not update objects held directlyand none of the first three schemes require users to code special python programs that do nothing but register handlers to be run later it is perhaps more commonthoughto register callback handlers with the last approach--letting python code register handlers with by calling back to through extension interfaces although this scheme is not without trade-offsit can provide natural and direct model in scenarios where callbacks are associated with large number of objects for instanceconsider gui constructed by building tree of widget objects in python scripts if each widget object in the tree can have an associated event handlerit may be easier to register handlers by simply calling methods of widgets in the tree associating handlers with widget objects in separate structure such as module file or an xml file requires extra cross-reference work to keep the handlers in sync with the tree in factif you're looking for more realistic example of python callback handlersconsider the tkinter gui system we've used extensively in this book tkinter uses both python/ integration |
6,094 | python callback handlerswhich are later run with embedding interfaces in response to gui events you can study tkinter' implementation in the python source distribution for more detailsits tk library interface logic makes it somewhat challenging readbut the basic model it employs is straightforward registration implementation this section' and python files demonstrate the coding techniques used to implement explicitly registered callback handlers firstthe file in example - implements interfaces for registering python handlersas well as code to run those handlers in response to later eventsevent router the route_event function responds to an event by calling python function object previously passed from python to callback registration the register_handler function saves passed-in python function object pointer in global variable python scripts call register_handler through simple cregister extension module created by this file event trigger to simulate real-world eventsthe trigger_event function can be called from python through the generated module to trigger an event in other wordsthis example uses both the embedding and the extending interfaces we've already met to register and invoke python event handler code study example - for more on its operation example - pp \integrate\embed\regist\cregister #include #include /***********************************************/ code to route events to python object */note that we could run strings here instead */***********************************************static pyobject *handler null/keep python object in *void route_event(char *labelint countchar *crespyobject *args*pres/call python handler *args py_buildvalue("(si)"labelcount)pres pyeval_callobject(handlerargs)py_decref(args)/make arg-list */applyrun call */add error checks *registering callback handler objects |
6,095 | if (pres !null/use and decref handler result *pyarg_parse(pres" "&cres)printf("% \ "cres)py_decref(pres)/*****************************************************/ python extension module to register handlers */python imports this module to set handler objects */*****************************************************static pyobject register_handler(pyobject *selfpyobject *args/save python callable object *py_xdecref(handler)/called before*pyarg_parse(args"( )"&handler)/one argument *py_xincref(handler)/add reference *py_incref(py_none)/return 'none'success *return py_nonestatic pyobject trigger_event(pyobject *selfpyobject *args/let python simulate event caught by *static count route_event("spam"count++)py_incref(py_none)return py_nonestatic pymethoddef cregister_methods[{"sethandler"register_handlermeth_varargs""}{"triggerevent"trigger_eventmeth_varargs""}{nullnull null}/name&func*/end of table *static struct pymoduledef cregistermodule pymoduledef_head_init"cregister"/name of module *"cregister mod"/module documentationmay be null *- /size of per-interpreter module state- =in global vars *cregister_methods /link to methods table *}pymodinit_func pyinit_cregister(/called on first import *return pymodule_create(&cregistermodule) python/ integration |
6,096 | that embeds python (though could just as well be on topto compile it into dynamically loaded module filerun the makefile in example - on cygwin (and use something similar on other platformsas we learned earlier in this the resulting cregister dll file will be loaded when first imported by python script if it is placed in directory on python' module search path ( in or pythonpath settingsexample - pp \integrate\embed\regist\makefile regist #####################################################################cygwin makefile that builds cregister dll dynamically loaded extension module (shareable)which is imported by register py #####################################################################pylib /usr/local/bin pyinc /usr/local/include/python cmods cregister dll all$(cmodscregister dllcregister gcc cregister - - $(pyinc-shared - $(pylib-lpython - $cleanrm - pyc $(cmodsnow that we have extension module set to register and dispatch python handlersall we need are some python handlers the python module shown in example - defines two callback handler functions and imports the extension module to register handlers and trigger events example - pp \integrate\embed\regist\register py ""########################################################################in pythonregister for and handle event callbacks from the languagecompile and link the codeand launch this with 'python register py########################################################################""################################### calls these python functionshandle an eventreturn result ###################################def callback (labelcount)return 'callback =% number % (labelcountdef callback (labelcount)return 'callback =label count registering callback handler objects |
6,097 | python calls extension module to register handlerstrigger events ######################################import cregister print('\ntest :'cregister sethandler(callback for in range( )cregister triggerevent(print('\ntest :'cregister sethandler(callback for in range( )cregister triggerevent(register callback function simulate events caught by layer routes these events to callback that' it--the python/ callback integration is set to go to kick off the systemrun the python scriptit registers one handler functionforces three events to be triggeredand then changes the event handler and does it again/pp /integrate/embed/registmake - makefile regist gcc cregister - - /usr/local/include/python -shared - /usr/local/bin -lpython - cregister dll /pp /integrate/embed/registpython register py test callback =spam number callback =spam number callback =spam number test callback =spamspamspam callback =spamspamspamspam callback =spamspamspamspamspam this output is printed by the event router functionbut its content is the return values of the handler functions in the python module actuallysomething pretty wild is going on under the hood when python forces an event to triggercontrol flows between languages like this from python to the event router function from the event router function to the python handler function back to the event router function (where the output is printed and finally back to the python script that iswe jump from python to to python and back again along the waycontrol passes through both extending and embedding interfaces when the python callback handler is runningtwo python levels are activeand one level in the middle luckilythis just workspython' api is reentrantso you don' need to be concerned about python/ integration |
6,098 | trace through this example' output and code for more illumination herewe're moving on to the last quick example we have time and space to explore--in the name of symmetryusing python classes from using python classes in earlier in this we learned how to use +classes in python by wrapping them with swig but what about going the other way--using python classes from other languagesit turns out that this is really just matter of applying interfaces already shown recall that python scripts generate class instance objects by calling class objects as though they were functions to do this from (or ++)simply follow the same stepsimport class from modulebuild an arguments tupleand call it to generate an instance using the same api tools you use to call python functions once you've got an instanceyou can fetch its attributes and methods with the same tools you use to fetch globals out of module callables and attributes work the same everywhere they live to illustrate how this works in practiceexample - defines simple python class in module that we can utilize from example - pp \integrate\embed\pyclasss\module py call this class from to make objects class klassdef method(selfxy)return "brave % % (xyrun me from this is nearly as simple as it getsbut it' enough to illustrate the basics as usualmake sure that this module is on your python search path ( in the current directoryor one listed on your pythonpath setting)or else the import call to access it from will failjust as it would in python script as you surely know if you've gotten this far in this bookyou can make always use of this python class from python program as follows\pp \integrate\embed\pyclasspython import module object module klass(result object method('sir''robin'print(resultbrave sir robin import the file make class instance call class method using python classes in |
6,099 | takes bit more code the file in example - implements these steps by arranging calls to the appropriate python api tools example - pp \integrate\embed\pyclass\objects #include #include main(/run objects with low-level calls *char *arg ="sir"*arg ="robin"*cstrpyobject *pmod*pclass*pargs*pinst*pmeth*pres/instance module klass(*py_initialize()pmod pyimport_importmodule("module")pclass pyobject_getattrstring(pmod"klass")py_decref(pmod)pargs py_buildvalue("()")pinst pyeval_callobject(pclasspargs)py_decref(pclass)py_decref(pargs)/fetch module */fetch module class */call class(*/result instance method( , *pmeth pyobject_getattrstring(pinst"method")/fetch bound method *py_decref(pinst)pargs py_buildvalue("(ss)"arg arg )/convert to python *pres pyeval_callobject(pmethpargs)/call method( , *py_decref(pmeth)py_decref(pargs)pyarg_parse(pres" "&cstr)printf("% \ "cstr)py_decref(pres)/convert to *step through this source file for more detailsit' mostly matter of figuring out how you would accomplish the task in pythonand then calling equivalent functions in the python api to build this source into executable programrun the makefile in this file' directory in the book examples package (it' analogous to makefiles we've already seenso we'll omit it hereafter compilingrun it as you would any other program/pp /integrate/embed/pyclass/objects brave sir robin this output might seem anticlimacticbut it actually reflects the return values sent back to by the python class method in file module py did lot of work to get this little string--it imported the modulefetched the classmade an instanceand fetched and called the instance method with tuple of argumentsperforming data conversions and python/ integration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.