id
int64
0
25.6k
text
stringlengths
0
4.59k
4,600
suefile open('sue pkl''wb'pickle dump(suesuefilesuefile close(here are our file-per-record scripts in actionthe results are about the same as in the prior sectionbut database keys become real filenames now in sensethe filesystem becomes our top-level dictionary--filenames provide direct access to each record \pp \previewpython make_db_pickle_recs py \pp \previewpython dump_db_pickle_recs py bob pkl ={'pay' 'job''dev''age' 'name''bob smith'sue pkl ={'pay' 'job''hdw''age' 'name''sue jones'tom pkl ={'pay' 'job'none'age' 'name''tom'sue jones \pp \previewpython update_db_pickle_recs py \pp \previewpython dump_db_pickle_recs py bob pkl ={'pay' 'job''dev''age' 'name''bob smith'sue pkl ={'pay' 'job''hdw''age' 'name''sue jones'tom pkl ={'pay' 'job'none'age' 'name''tom'sue jones using shelves pickling objects to filesas shown in the preceding sectionis an optimal scheme in many applications in factsome applications use pickling of python objects across network sockets as simpler alternative to network protocols such as the soap and xml-rpc web services architectures (also supported by pythonbut much heavier than picklemoreoverassuming your filesystem can handle as many files as you'll needpickling one record per file also obviates the need to load and store the entire database for each update if we really want keyed access to recordsthoughthe python standard library offers an even higher-level toolshelves shelves automatically pickle objects to and from keyed-access filesystem they behave much like dictionaries that must be openedand they persist after each program exits because they give us key-based access to stored recordsthere is no need to manually manage one flat file per record--the shelve system automatically splits up stored records and fetches and updates only those records that are accessed and changed in this wayshelves provide utility similar to per-record pickle filesbut they are usually easier to code step storing records persistently
4,601
open and close calls in factto your codea shelve really does appear to be persistent dictionary of persistent objectspython does all the work of mapping its content to and from file for instanceexample - shows how to store our in-memory dictionary objects in shelve for permanent keeping example - pp \preview\make_db_shelve py from initdata import bobsue import shelve db shelve open('people-shelve'db['bob'bob db['sue'sue db close(this script creates one or more files in the current directory with the name peopleshelve as prefix (in python on windowspeople-shelve bakpeople-shelve datand people-shelve diryou shouldn' delete these files (they are your database!)and you should be sure to use the same base name in other scripts that access the shelve example - for instancereopens the shelve and indexes it by key to fetch its stored records example - pp \preview\dump_db_shelve py import shelve db shelve open('people-shelve'for key in dbprint(key'=>\ 'db[key]print(db['sue']['name']db close(we still have dictionary of dictionaries herebut the top-level dictionary is really shelve mapped onto file much happens when you access shelve' keys--it uses pickle internally to serialize and deserialize objects storedand it interfaces with keyed-access filesystem from your perspectivethoughit' just persistent dictionary example - shows how to code shelve updates example - pp \preview\update_db_shelve py from initdata import tom import shelve db shelve open('people-shelve'sue db['sue'sue['pay'* db['sue'sue db['tom'tom db close(fetch sue update sue add new record notice how this code fetches sue by keyupdates in memoryand then reassigns to the key to update the shelvethis is requirement of shelves by defaultbut not always of more advanced shelve-like systems such as zodbcovered in as we'll see sneak preview
4,602
truecauses all records loaded from the shelve to be cached in memoryand automatically written back to the shelve when it is closedthis avoids manual write backs on changesbut can consume memory and make closing slow also note how shelve files are explicitly closed although we don' need to pass mode flags to shelve open (by default it creates the shelve if neededand opens it for reads and writes otherwise)some underlying keyed-access filesystems may require close call in order to flush output buffers after changes finallyhere are the shelve-based scripts on the jobcreatingchangingand fetching records the records are still dictionariesbut the database is now dictionary-like shelve which automatically retains its state in file between program runs\pp \previewpython make_db_shelve py \pp \previewpython dump_db_shelve py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'sue jones \pp \previewpython update_db_shelve py \pp \previewpython dump_db_shelve py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'tom ={'pay' 'job'none'age' 'name''tom'sue jones when we ran the update and dump scripts herewe added new record for key tom and increased sue' pay field by percent these changes are permanent because the record dictionaries are mapped to an external file by shelve (in factthis is particularly good script for sue--something she might consider scheduling to run oftenusing cron job on unixor startup folder or msconfig entry on windows what' in namethough it' surprisingly well-kept secretpython gets its name from the british tv comedy series monty python' flying circus according to python folkloreguido van rossumpython' creatorwas watching reruns of the show at about the same time he needed name for new language he was developing and as they say in show business"the rest is history because of this heritagereferences to the comedy group' work often show up in examples and discussion for instancethe name brian appears often in scriptsthe words spamlumberjackand shrubbery have special connotation to python usersand presentations are sometimes referred to as the spanish inquisition as ruleif python user starts using phrases that have no relation to realitythey're probably borrowed step storing records persistently
4,603
this book you don' have to run out and rent the meaning of life or the holy grail to do useful work in pythonof coursebut it can' hurt while "pythonturned out to be distinctive nameit has also had some interesting side effects for instancewhen the python newsgroupcomp lang pythoncame online in its first few weeks of activity were almost entirely taken up by people wanting to discuss topics from the tv show more recentlya special python supplement in the linux journal magazine featured photos of guido garbed in an obligatory "nice red uniform python' news list still receives an occasional post from fans of the show for instanceone early poster innocently offered to swap monty python scripts with other fans had he known the nature of the forumhe might have at least mentioned whether they were portable or not step stepping up to oop let' step back for moment and consider how far we've come at this pointwe've created database of recordsthe shelveas well as per-record pickle file approaches of the prior section suffice for basic data storage tasks as isour records are represented as simple dictionarieswhich provide easier-to-understand access to fields than do lists (by keyrather than by positiondictionarieshoweverstill have some limitations that may become more critical as our program grows over time for one thingthere is no central place for us to collect record processing logic extracting last names and giving raisesfor instancecan be accomplished with code like the followingimport shelve db shelve open('people-shelve'bob db['bob'bob['name'split()[- 'smithsue db['sue'sue['pay'* sue['pay' db['sue'sue db close(get bob' last name give sue raise this worksand it might suffice for some short programs but if we ever need to change the way last names and raises are implementedwe might have to update this kind of code in many places in our program in facteven finding all such magical code snippets could be challengehardcoding or cutting and pasting bits of logic redundantly like this in more than one place will almost always come back to haunt you eventually it would be better to somehow hide--that isencapsulate--such bits of code functions in module would allow us to implement such operations in single place and thus sneak preview
4,604
themselves what we' like is way to bind processing logic with the data stored in the database in order to make it easier to understanddebugand reuse another downside to using dictionaries for records is that they are difficult to expand over time for examplesuppose that the set of data fields or the procedure for giving raises is different for different kinds of people (perhaps some people get bonus each year and some do notif we ever need to extend our programthere is no natural way to customize simple dictionaries for future growthwe' also like our software to support extension and customization in natural way if you've already studied python in any sort of depthyou probably already know that this is where its oop support begins to become attractivestructure with oopwe can naturally associate processing logic with record data--classes provide both program unit that combines logic and data in single package and hierarchy that allows code to be easily factored to avoid redundancy encapsulation with oopwe can also wrap up details such as name processing and pay increases behind method functions-- we are free to change method implementations without breaking their users customization and with oopwe have natural growth path classes can be extended and customized by coding new subclasseswithout changing or breaking already working code that isunder oopwe program by customizing and reusingnot by rewriting oop is an option in python andfranklyis sometimes better suited for strategic than for tactical tasks it tends to work best when you have time for upfront planning--something that might be luxury if your users have already begun storming the gates but especially for larger systems that change over timeits code reuse and structuring advantages far outweigh its learning curveand it can substantially cut development time even in our simple casethe customizability and reduced redundancy we gain from classes can be decided advantage using classes oop is easy to use in pythonthanks largely to python' dynamic typing model in factit' so easy that we'll jump right into an exampleexample - implements our database records as class instances rather than as dictionaries example - pp \preview\person_start py class persondef __init__(selfnameagepay= job=none)step stepping up to oop
4,605
self age age self pay pay self job job if __name__ ='__main__'bob person('bob smith' 'software'sue person('sue jones' 'hardware'print(bob namesue payprint(bob name split()[- ]sue pay * print(sue paythere is not much to this class--just constructor method that fills out the instance with data passed in as arguments to the class name it' sufficient to represent database recordthoughand it can already provide tools such as defaults for pay and job fields that dictionaries cannot the self-test code at the bottom of this file creates two instances (recordsand accesses their attributes (fields)here is this file' output when run under idle ( system command-line works just as well)bob smith smith this isn' database yetbut we could stuff these objects into list or dictionary as before in order to collect them as unitfrom person_start import person bob person('bob smith' sue person('sue jones' people [bobsuefor person in peopleprint(person nameperson paya "databaselist bob smith sue jones [(person nameperson payfor person in peoplex [('bob smith' )('sue jones' )[rec name for rec in people if rec age > ['sue jones'sql-ish query [(rec age * if rec age > else rec agefor rec in people[ notice that bob' pay defaulted to zero this time because we didn' pass in value for that argument (maybe sue is supporting him now?we might also implement class that represents the databaseperhaps as subclass of the built-in list or dictionary typeswith insert and delete methods that encapsulate the way the database is implemented we'll abandon this path for nowthoughbecause it will be more useful to store these sneak preview
4,606
an interface for us before we dothoughlet' add some logic adding behavior so farour class is just datait replaces dictionary keys with object attributesbut it doesn' add much to what we had before to really leverage the power of classeswe need to add some behavior by wrapping up bits of behavior in class method functionswe can insulate clients from changes and by packaging methods in classes along with datawe provide natural place for readers to look for code in senseclasses combine records and the programs that process those recordsmethods provide logic that interprets and updates the data (we say they are object-orientedbecause they always process an object' datafor instanceexample - adds the last-name and raise logic as class methodsmethods use the self argument to access or update the instance (recordbeing processed example - pp \preview\person py class persondef __init__(selfnameagepay= job=none)self name name self age age self pay pay self job job def lastname(self)return self name split()[- def giveraise(selfpercent)self pay *( percentif __name__ ='__main__'bob person('bob smith' 'software'sue person('sue jones' 'hardware'print(bob namesue payprint(bob lastname()sue giveraise print(sue paythe output of this script is the same as the lastbut the results are being computed by methods nownot by hardcoded logic that appears redundantly wherever it is requiredbob smith smith adding inheritance one last enhancement to our records before they become permanentbecause they are implemented as classes nowthey naturally support customization through the inheritance search mechanism in python example - for instancecustomizes the last step stepping up to oop
4,607
example - pp \preview\manager py from person import person class manager(person)def giveraise(selfpercentbonus= )self pay *( percent bonusif __name__ ='__main__'tom manager(name='tom doe'age= pay= print(tom lastname()tom giveraise print(tom paywhen runthis script' self-test prints the followingdoe herethe manager class appears in module of its ownbut it could have been added to the person module instead (python doesn' require just one class per fileit inherits the constructor and last-name methods from its superclassbut it customizes just the giveraise method (there are variety of ways to code this extensionas we'll see laterbecause this change is being added as new subclassthe original person classand any objects generated from itwill continue working unchanged bob and suefor exampleinherit the original raise logicbut tom gets the custom version because of the class from which he is created in oopwe program by customizingnot by changing in factcode that uses our objects doesn' need to be at all aware of what the raise method does--it' up to the object to do the right thing based on the class from which it is created as long as the object supports the expected interface (herea method called giveraise)it will be compatible with the calling coderegardless of its specific typeand even if its method works differently than others if you've already studied pythonyou may know this behavior as polymorphismit' core property of the languageand it accounts for much of your code' flexibility when the following code calls the giveraise methodfor examplewhat happens depends on the obj object being processedtom gets percent raise instead of percent because of the manager class' customizationfrom person import person from manager import manager bob person(name='bob smith'age= pay= sue person(name='sue jones'age= pay= tom manager(name='tom doe'age= pay= db [bobsuetom sneak preview
4,608
obj giveraise default or custom for obj in dbprint(obj lastname()'=>'obj paysmith = jones = doe = refactoring code before we move onthere are few coding alternatives worth noting here most of these underscore the python oop modeland they serve as quick review augmenting methods as first alternativenotice that we have introduced some redundancy in example - the raise calculation is now repeated in two places (in the two classeswe could also have implemented the customized manager class by augmenting the inherited raise method instead of replacing it completelyclass manager(person)def giveraise(selfpercentbonus= )person giveraise(selfpercent bonusthe trick here is to call back the superclass' version of the method directlypassing in the self argument explicitly we still redefine the methodbut we simply run the general version after adding percent (by defaultto the passed-in percentage this coding pattern can help reduce code redundancy (the original raise method' logic appears in only one place and so is easier to changeand is especially handy for kicking off superclass constructor methods in practice if you've already studied python oopyou know that this coding scheme works because we can always call methods through either an instance or the class name in generalthe following are equivalentand both forms may be used explicitlyinstance method(arg arg class method(instancearg arg in factthe first form is mapped to the second--when calling through the instancepython determines the class by searching the inheritance tree for the method name and passes in the instance automatically either waywithin giveraiseself refers to the instance that is the subject of the call display format for more object-oriented funwe could also add few operator overloading methods to our people classes for examplea __str__ methodshown herecould return string step stepping up to oop
4,609
better than the default display we get for an instanceclass persondef __str__(self)return % >(self __class__ __name__self nametom manager('tom jones' print(tomprintstom joneshere __class__ gives the lowest class from which self was madeeven though __str__ may be inherited the net effect is that __str__ allows us to print instances directly instead of having to print specific attributes we could extend this __str__ to loop through the instance' __dict__ attribute dictionary to display all attributes genericallyfor this preview we'll leave this as suggested exercise we might even code an __add__ method to make expressions automatically call the giveraise method whether we should is another questionthe fact that expression gives person raise might seem more magical to the next person reading our code than it should constructor customization finallynotice that we didn' pass the job argument when making manager in example - if we hadit would look like this with keyword argumentstom manager(name='tom doe'age= pay= job='manager'the reason we didn' include job in the example is that it' redundant with the class of the objectif someone is managertheir class should imply their job title instead of leaving this field blankthoughit may make more sense to provide an explicit constructor for managerswhich fills in this field automaticallyclass manager(person)def __init__(selfnameagepay)person __init__(selfnameagepay'manager'now when manager is createdits job is filled in automatically the trick here is to call to the superclass' version of the method explicitlyjust as we did for the giveraise method earlier in this sectionthe only difference here is the unusual name for the constructor method alternative classes we won' use any of this section' three extensions in later examplesbut to demonstrate how they workexample - collects these ideas in an alternative implementation of our person classes sneak preview
4,610
""alternative implementation of person classeswith databehaviorand operator overloading (not used for objects stored persistently""class person"" general persondata+logic ""def __init__(selfnameagepay= job=none)self name name self age age self pay pay self job job def lastname(self)return self name split()[- def giveraise(selfpercent)self pay *( percentdef __str__(self)return (% % % >(self __class__ __name__self nameself jobself pay)class manager(person)"" person with custom raise inherits general lastnamestr ""def __init__(selfnameagepay)person __init__(selfnameagepay'manager'def giveraise(selfpercentbonus= )person giveraise(selfpercent bonusif __name__ ='__main__'bob person('bob smith' sue person('sue jones' 'hardware'tom manager(name='tom doe'age= pay= print(suesue paysue lastname()for obj in (bobsuetom)obj giveraise run this obj' giveraise print(objrun common __str__ method notice the polymorphism in this module' self-test loopall three objects share the constructorlast-nameand printing methodsbut the raise method called is dependent upon the class from which an instance is created when runexample - prints the following to standard output--the manager' job is filled in at constructionwe get the new custom display format for our objectsand the new version of the manager' raise method works as beforesue joneshardware jones bob smithnone sue joneshardware tom doemanager step stepping up to oop
4,611
in factas iswe still can' give someone raise if his pay is zero (bob is out of luck)we probably need way to set paytoobut we'll leave such extensions for the next release the good news is that python' flexibility and readability make refactoring easy--it' simple and quick to restructure your code if you haven' used the language yetyou'll find that python development is largely an exercise in rapidincrementaland interactive programmingwhich is well suited to the shifting needs of real-world projects adding persistence it' time for status update we now have encapsulated in the form of classes customizable implementations of our records and their processing logic making our classbased records persistent is minor last step we could store them in per-record pickle files againa shelve-based storage medium will do just as well for our goals and is often easier to code example - shows how example - pp \preview\make_db_classes py import shelve from person import person from manager import manager bob person('bob smith' 'software'sue person('sue jones' 'hardware'tom manager('tom doe' db shelve open('class-shelve'db['bob'bob db['sue'sue db['tom'tom db close(this file creates three class instances (two from the original class and one from its customizationand assigns them to keys in newly created shelve file to store them permanently in other wordsit creates shelve of class instancesto our codethe database looks just like dictionary of class instancesbut the top-level dictionary is mapped to shelve file again to check our workexample - reads the shelve and prints fields of its records example - pp \preview\dump_db_classes py import shelve db shelve open('class-shelve'for key in dbprint(key'=>\ 'db[keynamedb[keypaybob db['bob'print(bob lastname()print(db['tom'lastname() sneak preview
4,612
from the shelve or run their methods when instances are shelved or pickledthe underlying pickling system records both instance attributes and enough information to locate their classes automatically when they are later fetched (the class' module simply has to be on the module search path when an instance is loadedthis is on purposebecause the class and its instances in the shelve are stored separatelyyou can change the class to modify the way stored instances are interpreted when loaded (more on this later in the bookhere is the shelve dump script' output just after creating the shelve with the maker scriptbob =bob smith sue =sue jones tom =tom doe smith doe as shown in example - database updates are as simple as before (compare this to example - )but dictionary keys become attributes of instance objectsand updates are implemented by class method calls instead of hardcoded logic notice how we still fetchupdateand reassign to keys to update the shelve example - pp \preview\update_db_classes py import shelve db shelve open('class-shelve'sue db['sue'sue giveraise db['sue'sue tom db['tom'tom giveraise db['tom'tom db close(and last but not leasthere is the dump script again after running the update scripttom and sue have new pay valuesbecause these objects are now persistent in the shelve we could also open and inspect the shelve by typing code at python' interactive command linedespite its longevitythe shelve is just python object containing python objects bob =bob smith sue =sue jones tom =tom doe smith doe step stepping up to oop
4,613
the shelve database although shelves can also store simpler object types such as lists and dictionariesclass instances allow us to combine both data and behavior for our stored items in senseinstance attributes and class methods take the place of records and processing programs in more traditional schemes other database options at this pointwe have full-fledged database systemour classes simultaneously implement record data and record processingand they encapsulate the implementation of the behavior and the python pickle and shelve modules provide simple ways to store our database persistently between program executions this is not relational database (we store objectsnot tablesand queries take the form of python object processing code)but it is sufficient for many kinds of programs if we need more functionalitywe could migrate this application to even more powerful tools for exampleshould we ever need full-blown sql query supportthere are interfaces that allow python scripts to communicate with relational databases such as mysqlpostgresqland oracle in portable ways orms (object relational mapperssuch as sqlobject and sqlalchemy offer another approach which retains the python class viewbut translates it to and from relational database tables--in sense providing the best of both worldswith python class syntax on topand enterprise-level databases underneath moreoverthe open source zodb system provides more comprehensive object database for pythonwith support for features missing in shelvesincluding concurrent updatestransaction commits and rollbacksautomatic updates on in-memory component changesand more we'll explore these more advanced third-party tools in for nowlet' move on to putting good face on our system "buses considered harmfulover the yearspython has been remarkably well supported by the volunteer efforts of both countless individuals and formal organizations todaythe nonprofit python software foundation (psfoversees python conferences and other noncommercial activities the psf was preceded by the psaa group that was originally formed in response to an early thread on the python newsgroup that posed the semiserious question"what would happen if guido was hit by bus?these dayspython creator guido van rossum is still the ultimate arbiter of proposed python changes he was officially anointed the bdfl--benevolent dictator for life-of python at the first python conference and still makes final yes and no decisions on language changes (and apart from ' deliberate incompatibilitieshas usually said noa good thing in the programming languages domainbecause python tends to change slowly and in backward-compatible ways sneak preview
4,614
so on it is true community project in factpython development is now completely open process--anyone can inspect the latest source code files or submit patches by visiting website (see as an open source packagepython development is really in the hands of very large cast of developers working in concert around the world--so much so that if the bdfl ever does pass the torchpython will almost certainly continue to enjoy the kind of support its users have come to expect though not without pitfalls of their ownopen source projects by nature tend to reflect the needs of their user communities more than either individuals or shareholders given python' popularitybus attacks seem less threatening now than they once did of coursei can' speak for guido step adding console interaction so farour database program consists of class instances stored in shelve fileas coded in the preceding section it' sufficient as storage mediumbut it requires us to run scripts from the command line or type code interactively in order to view or process its content improving on this is straightforwardsimply code more general programs that interact with userseither from console window or from full-blown graphical interface console shelve interface let' start with something simple the most basic kind of interface we can code would allow users to type keys and values in console window in order to process the database (instead of writing python program codeexample - for instanceimplements simple interactive loop that allows user to query multiple record objects in the shelve by key example - pp \preview\peopleinteract_query py interactive queries import shelve fieldnames ('name''age''job''pay'maxfield max(len(ffor in fieldnamesdb shelve open('class-shelve'while truekey input('\nkey='if not keybreak tryrecord db[keykey or empty lineexc at eof fetch by keyshow in console step adding console interaction
4,615
print('no such key "% "!keyelsefor field in fieldnamesprint(field ljust(maxfield)'=>'getattr(recordfield)this script uses the getattr built-in function to fetch an object' attribute when given its name stringand the ljust left-justify method of strings to align outputs (max fieldderived from generator expressionis the length of the longest field namewhen runthis script goes into loopinputting keys from the interactive user (technicallyfrom the standard input streamwhich is usually console windowand displaying the fetched records field by field an empty line ends the session if our shelve of class instances is still in the state we left it near the end of the last section\pp \previewdump_db_classes py bob =bob smith sue =sue jones tom =tom doe smith doe we can then use our new script to query the object database interactivelyby key\pp \previewpeopleinteract_query py key=sue name =sue jones age = job =hardware pay = key=nobody no such key "nobody"key=example - goes further and allows interactive updates for an input keyit inputs values for each field and either updates an existing record or creates new object and stores it under the key example - pp \preview\peopleinteract_update py interactive updates import shelve from person import person fieldnames ('name''age''job''pay'db shelve open('class-shelve'while truekey input('\nkey='if not keybreak sneak preview
4,616
record db[keyupdate existing record elseor make/store new rec record person(name='?'age='?'evalquote strings for field in fieldnamescurrval getattr(recordfieldnewtext input('\ [% ]=% \ \ \tnew?=>(fieldcurrval)if newtextsetattr(recordfieldeval(newtext)db[keyrecord db close(notice the use of eval in this script to convert inputs (as usualthat allows any python object typebut it means you must quote string inputs explicitlyand the use of setattr call to assign an attribute given its name string when runthis script allows any number of records to be added and changedto keep the current value of record' fieldpress the enter key when prompted for new valuekey=tom [name]=tom doe new?=[age]= new?=> [job]=none new?=>'mgr[pay]= new?=> key=nobody [name]=new?=>'john doh[age]=new?=> [job]=none new?=[pay]= new?=>none key=this script is still fairly simplistic ( errors aren' handled)but using it is much easier than manually opening and modifying the shelve at the python interactive promptespecially for nonprogrammers run the query script to check your work after an update (we could combine query and update into single script if this becomes too cumbersomealbeit at some cost in code and user-experience complexity)key=tom name =tom doe age = job =mgr pay = key=nobody name =john doh step adding console interaction
4,617
job pay = =none =none key=step adding gui the console-based interface approach of the preceding section worksand it may be sufficient for some users assuming that they are comfortable with typing commands in console window with just little extra workthoughwe can add gui that is more moderneasier to useless error proneand arguably sexier gui basics as we'll see later in this booka variety of gui toolkits and builders are available for python programmerstkinterwxpythonpyqtpythoncarddaboand more of thesetkinter ships with pythonand it is something of de facto standard tkinter is lightweight toolkit and so meshes well with scripting language such as pythonit' easy to do basic things with tkinterand it' straightforward to do more advanced things with extensions and oop-based code as an added bonustkinter guis are portable across windowslinux/unixand macintoshsimply copy the source code to the machine on which you wish to use your gui tkinter doesn' come with all the bells and whistles of larger toolkits such as wxpython or pyqtbut that' major factor behind its relative simplicityand it makes it ideal for getting started in the gui domain because tkinter is designed for scriptingcoding guis with it is straightforward we'll study all of its concepts and tools later in this book but as first examplethe first program in tkinter is just few lines of codeas shown in example - example - pp \preview\tkinter py from tkinter import label(text='spam'pack(mainloop(from the tkinter module (reallya module package in python )we get screen device ( "widget"construction calls such as labelgeometry manager methods such as packwidget configuration presets such as the top and right attachment side hints we'll use later for packand the mainloop callwhich starts event processing this isn' the most useful gui ever codedbut it demonstrates tkinter basics and it builds the fully functional window shown in figure - in just three simple lines of code its window is shown herelike all guis in this bookrunning on windows it works the same on other platforms ( mac os xlinuxand older versions of windows)but renders in with native look and feel on each sneak preview
4,618
you can launch this example in idlefrom console command lineor by clicking its icon--the same way you can run other python scripts tkinter itself is standard part of python and works out-of-the-box on windows and othersthough you may need extra configuration or install steps on some computers (more details later in this bookit' not much more work to code gui that actually responds to userexample - implements gui with button that runs the reply function each time it is pressed example - pp \previewtkinter py from tkinter import from tkinter messagebox import showinfo def reply()showinfo(title='popup'message='button pressed!'window tk(button button(windowtext='press'command=replybutton pack(window mainloop(this example still isn' very sophisticated--it creates an explicit tk main window for the application to serve as the parent container of the buttonand it builds the simple window shown in figure - (in tkintercontainers are passed in as the first argument when making new widgetthey default to the main windowbut this timeeach time you click the "pressbuttonthe program responds by running python code that pops up the dialog window in figure - figure - tkinter py main window notice that the pop-up dialog looks like it should for windows the platform on which this screenshot was takenagaintkinter gives us native look and feel that is appropriate for the machine on which it is running we can customize this gui in many ways ( by changing colors and fontssetting window titles and iconsusing photos step adding gui
4,619
on buttons instead of text)but part of the power of tkinter is that we need to set only the options we are interested in tailoring using oop for guis all of our gui examples so far have been top-level script code with function for handling events in larger programsit is often more useful to code gui as subclass of the tkinter frame widget-- container for other widgets example - shows our single-button gui recoded in this way as class example - pp \preview\tkinter py from tkinter import from tkinter messagebox import showinfo class mygui(frame)def __init__(selfparent=none)frame __init__(selfparentbutton button(selftext='press'command=self replybutton pack(def reply(self)showinfo(title='popup'message='button pressed!'if __name__ ='__main__'window mygui(window pack(window mainloop(the button' event handler is bound method--self replyan object that remembers both self and reply when later called this example generates the same window and pop up as example - (figures - and - )but because it is now subclass of frameit automatically becomes an attachable component-- we can add all of the widgets this class createsas packageto any other guijust by attaching this frame to the gui example - shows how sneak preview
4,620
from tkinter import from tkinter import mygui main app window mainwin tk(label(mainwintext=__name__pack(popup window popup toplevel(label(popuptext='attach'pack(side=leftmygui(popuppack(side=rightmainwin mainloop(attach my frame this example attaches our one-button gui to larger windowhere toplevel popup window created by the importing application and passed into the construction call as the explicit parent (you will also get tk main windowas we'll learn lateryou always dowhether it is made explicit in your code or notour one-button widget package is attached to the right side of its container this time if you run this liveyou'll get the scene captured in figure - the "pressbutton is our attached custom frame figure - attaching guis moreoverbecause mygui is coded as classthe gui can be customized by the usual inheritance mechanismsimply define subclass that replaces the parts that differ the reply methodfor examplecan be customized this way to do something uniqueas demonstrated in example - example - pp \preview\customizegui py from tkinter import mainloop from tkinter messagebox import showinfo from tkinter import mygui step adding gui
4,621
def reply(self)showinfo(title='popup'message='ouch!'inherit init replace reply if __name__ ='__main__'customgui(pack(mainloop(when runthis script creates the same main window and button as the original mygui class but pressing its button generates different replyas shown in figure - because the custom version of the reply method runs figure - customizing guis although these are still small guisthey illustrate some fairly large ideas as we'll see later in the bookusing oop like this for inheritance and attachment allows us to reuse packages of widgets in other programs--calculatorstext editorsand the like can be customized and added as components to other guis easily if they are classes as we'll also findsubclasses of widget class can provide common appearance or standardized behavior for all their instances--similar in spirit to what some observers might call gui styles or themes it' normal byproduct of python and oop getting input from user as final introductory scriptexample - shows how to input data from the user in an entry widget and display it in pop-up dialog the lambda it uses defers the call to the reply function so that inputs can be passed in-- common tkinter coding patternwithout the lambdareply would be called when the button is madeinstead of when it is later pressed (we could also use ent as global variable within replybut that makes it less generalthis example also demonstrates how to change the icon and title of top-level windowherethe window icon file is located in the same directory as the script (if the icon call in this script fails on your platformtry commenting-out the callicons are notoriously platform specific sneak preview
4,622
from tkinter import from tkinter messagebox import showinfo def reply(name)showinfo(title='reply'message='hello % !nametop tk(top title('echo'top iconbitmap('py-blue-trans-out ico'label(toptext="enter your name:"pack(side=topent entry(topent pack(side=topbtn button(toptext="submit"command=(lambdareply(ent get()))btn pack(side=lefttop mainloop(as isthis example is just three widgets attached to the tk main top-level windowlater we'll learn how to use nested frame container widgets in window like this to achieve variety of layouts for its three widgets figure - gives the resulting main and popup windows after the submit button is pressed we'll see something very similar later in this but rendered in web browser with html figure - fetching input from user the code we've seen so far demonstrates many of the core concepts in gui programmingbut tkinter is much more powerful than these examples imply there are more than widgets in tkinter and many more ways to input data from userincluding multiple-line textdrawing canvasespull-down menusradio and check buttonsand scroll barsas well as other layout and event handling mechanisms beyond tkinter itselfboth open source extensions such as pmwas well as the tix and ttk toolkits now part of python' standard librarycan add additional widgets we can use in our step adding gui
4,623
what is to comelet' put tkinter to work on our database of people gui shelve interface for our database applicationthe first thing we probably want is gui for viewing the stored data-- form with field names and values--and way to fetch records by key it would also be useful to be able to update record with new field values given its key and to add new records from scratch by filling out the form to keep this simplewe'll use single gui for all of these tasks figure - shows the window we are going to code as it looks in windows the record for the key sue has been fetched and displayed (our shelve is as we last left it againthis record is really an instance of our class in our shelve filebut the user doesn' need to care figure - peoplegui py main display/input window coding the gui alsoto keep this simplewe'll assume that all records in the database have the same sets of fields it would be minor extension to generalize this for any set of fields (and come up with general form gui constructor tool in the process)but we'll defer such evolutions to later in this book example - implements the gui shown in figure - example - pp \preview\peoplegui py ""implement gui for viewing and updating class instances stored in shelvethe shelve lives on the machine this script runs onas or more local files""from tkinter import from tkinter messagebox import showerror import shelve shelvename 'class-shelvefieldnames ('name''age''job''pay' sneak preview
4,624
global entries window tk(window title('people shelve'form frame(windowform pack(entries {for (ixlabelin enumerate(('key',fieldnames)lab label(formtext=labelent entry(formlab grid(row=ixcolumn= ent grid(row=ixcolumn= entries[labelent button(windowtext="fetch"command=fetchrecordpack(side=leftbutton(windowtext="update"command=updaterecordpack(side=leftbutton(windowtext="quit"command=window quitpack(side=rightreturn window def fetchrecord()key entries['key'get(tryrecord db[keyfetch by keyshow in gui exceptshowerror(title='error'message='no such key!'elsefor field in fieldnamesentries[fielddelete( endentries[fieldinsert( repr(getattr(recordfield))def updaterecord()key entries['key'get(if key in dbrecord db[keyupdate existing record elsefrom person import person make/store new one for key record person(name='?'age='?'evalstrings must be quoted for field in fieldnamessetattr(recordfieldeval(entries[fieldget())db[keyrecord db shelve open(shelvenamewindow makewidgets(window mainloop(db close(back here after quit or window close this script uses the widget grid method to arrange labels and entriesinstead of packas we'll see latergridding arranges by rows and columnsand so it is natural for forms that horizontally align labels with entries well we'll also see later that forms can usually be laid out just as nicely using pack with nested row frames and fixed-width labels although the gui doesn' handle window resizes well yet (that requires configuration options we'll explore later)adding this makes the grid and pack alternatives roughly the same in code size step adding gui
4,625
guithe shelve remains open for the lifespan of the gui (mainloop returns only after the main window is closedas we'll see in the next sectionthis state retention is very different from the web modelwhere each interaction is normally standalone program also notice that the use of global variables makes this code simple but unusable outside the context of our databasemore on this later using the gui the gui we're building is fairly basicbut it provides view on the shelve file and allows us to browse and update the file without typing any code to fetch record from the shelve and display it on the guitype its key into the gui' "keyfield and click fetch to change recordtype into its input fields after fetching it and click updatethe values in the gui will be written to the record in the database and to add new recordfill out all of the gui' fields with new values and click update--the new record will be added to the shelve file using the key and field inputs you provide in other wordsthe gui' fields are used for both display and input figure - shows the scene after adding new record (via update)and figure - shows an error dialog pop up issued when users try to fetch key that isn' present in the shelve figure - peoplegui py after adding new persistent object figure - peoplegui py common error dialog pop up sneak preview
4,626
eval to convert field values to python objects before they are stored in the shelve as mentioned previouslythis is potentially dangerous if someone sneaks some malicious code into our shelvebut we'll finesse such concerns for now keep in mindthoughthat this scheme means that strings must be quoted in input fields other than the key--they are assumed to be python code in factyou could type an arbitrary python expression in an input field to specify value for an update typing "tom"* in the name fieldfor instancewould set the name to tomtomtom after an update (for better or worse!)fetch to see the result even though we now have gui for browsing and changing recordswe can still check our work by interactively opening and inspecting the shelve file or by running scripts such as the dump utility in example - rememberdespite the fact that we're now viewing records in gui' windowsthe database is python shelve file containing native python class instance objectsso any python code can access it here is the dump script at work after adding and changing few persistent objects in the gui\pp \previewpython dump_db_classes py sue =sue jones bill =bill nobody =john doh none tomtom =tom tom tom =tom doe bob =bob smith peg = smith doe future directions although this gui does the jobthere is plenty of room for improvementas codedthis gui is simple set of functions that share the global list of input fields (entriesand global shelve (dbwe might instead pass db in to makewidgetsand pass along both these two objects as function arguments to the callback handlers using the lambda trick of the prior section though not crucial in script this smallas rule of thumbmaking your external dependencies explicit like this makes your code both easier to understand and reusable in other contexts we could also structure this gui as class to support attachment and customization (globals would become instance attributes)though it' unlikely that we'll need to reuse such specific gui step adding gui
4,627
functions here to allow them to be used for other record types in the future code at the bottom of the file would similarly become function with passed-in shelve filenameand we would also need to pass in new record construction call to the update function because person could not be hardcoded such generalization is beyond the scope of this previewbut it makes for nice exercise if you are so inclined lateri'll also point you to suggested reading example in the book examples packagepyformwhich takes different approach to generalized form construction to make this gui more user friendlyit might also be nice to add an index window that displays all the keys in the database in order to make browsing easier some sort of verification before updates might be useful as welland delete and clear buttons would be simple to code furthermoreassuming that inputs are python code may be more bother than it is wortha simpler input scheme might be easier and safer ( won' officially say these are suggested exercises toobut it sounds like they could be we could also support window resizing (as we'll learnwidgets can grow and shrink with the windowand provide an interface for calling methods available on stored instancesclasses too (as isthe pay field can be updatedbut there is no way to invoke the giveraise methodif we plan to distribute this gui widelywe might package it up as standalone executable program-- frozen binary in python terminology--using third-party tools such as py exepyinstallerand others (search the web for pointerssuch program can be run directly without installing python on the receiving endbecause the python bytecode interpreter is included in the executable itself 'll leave all such extensions as points to ponderand revisit some of them later in this book before we move ontwo notes firsti should mention that even more graphical packages are available to python programmers for instanceif you need to do graphics beyond basic windowsthe tkinter canvas widget supports freeform graphics thirdparty extensions such as blenderopenglvpythonpilvtkmayaand pygame provide even more advanced graphicsvisualizationand animation tools for use with python scripts moreoverthe pmwtixand ttk widget kits mentioned earlier extend tkinter itself see python' library manual for tix and ttkand try the pypi site or web search for third-party graphics extensions and in deference to fans of other gui toolkits such as wxpython and pyqti should also note that there are other gui options to choose from and that choice is sometimes very subjective tkinter is shown here because it is maturerobustfully open sourcewell documentedwell supportedlightweightand standard part of python by most accountsit remains the standard for building portable guis in python sneak preview
4,628
book for examplesome exchange code simplicity for richer widget sets wxpythonfor exampleis much more feature-richbut it' also much more complicated to use by and largethoughother toolkits are variations on theme--once you've learned one gui toolkitothers are easy to pick up because of thatwe'll focus on learning one toolkit in its entirety in this book instead of sampling many partially although they are free to employ network access at willprograms written with traditional guis like tkinter generally run on singleself-contained machine some consider web pages to be kind of gui as wellbut you'll have to read the next and final section of this to judge that for yourself for good time there' much more to the tkinter toolkit than we've touched on in this previewof courseand we'll study it in depth in this book as another quick example to hint at what' possiblethoughthe following scriptfungui pyuses the python random module to pick from listmakes new independent windows with topleveland uses the tkinter after callback to loop by scheduling methods to run again after number of millisecondsfrom tkinter import import random fontsize colors ['red''green''blue''yellow''orange''cyan''purple'def onspam()popup toplevel(color random choice(colorslabel(popuptext='popup'bg='black'fg=colorpack(fill=bothmainlabel config(fg=colordef onflip()mainlabel config(fg=random choice(colors)main after( onflipdef ongrow()global fontsize fontsize + mainlabel config(font=('arial'fontsize'italic')main after( ongrowmain tk(mainlabel label(maintext='fun gui!'relief=raisedmainlabel config(font=('arial'fontsize'italic')fg='cyan',bg='navy'mainlabel pack(side=topexpand=yesfill=bothbutton(maintext='spam'command=onspampack(fill=xbutton(maintext='flip'command=onflippack(fill=xbutton(maintext='grow'command=ongrowpack(fill=xmain mainloop(run this on your own to see how it works it creates main window with custom label and three buttons--one button pops up new window with randomly colored labeland the other two kick off potentially independent timer loopsone of which step adding gui
4,629
the main window label' font be careful if you do run thisthoughthe colors flashand the label font gets bigger times per secondso be sure you are able to kill the main window before it gets away from you hey-- warned youstep adding web interface gui interfaces are easier to use than command lines and are often all we need to simplify access to data by making our database available on the webthoughwe can open it up to even wider use anyone with internet access and web browser can access the dataregardless of where they are located and which machine they are using anything from workstations to cell phones will suffice moreoverweb-based interfaces require only web browserthere is no need to install python to access the data except on the single-server machine although traditional web-based approaches may sacrifice some of the utility and speed of in-process gui toolkitstheir portability gain can be compelling as we'll also see later in this bookthere are variety of ways to go about scripting interactive web pages of the sort we'll need in order to access our data basic serverside cgi scripting is more than adequate for simple tasks like ours because it' perhaps the simplest approachand embodies the foundations of more advanced techniquescgi scripting is also well-suited to getting started on the web for more advanced applicationsa wealth of toolkits and frameworks for python-including djangoturbogearsgoogle' app enginepylonsweb pyzopeplonetwistedcherrypywebwaremod_pythonpspand quixote--can simplify common tasks and provide tools that we might otherwise need to code from scratch in the cgi world though they pose new set of tradeoffsemerging technologies such as flexsilverlightand pyjamas (an ajax-based port of the google web toolkit to pythonand python-to-javascript compileroffer additional paths to achieving interactive or dynamic user-interfaces in web pages on clientsand open the door to using python in rich internet applications (riasi'll say more about these tools later for nowlet' keep things simple and code cgi script cgi basics cgi scripting in python is easy as long as you already have handle on things like html formsurlsand the client/server model of the web (all topics we'll address in detail later in this bookwhether you're aware of all the underlying details or notthe basic interaction model is probably familiar in nutshella user visits website and receives formcoded in htmlto be filled out in his or her browser after submitting the forma scriptidentified within either sneak preview
4,630
another html page as reply along the waydata typically passes through three programsfrom the client browserto the web serverto the cgi scriptand back again to the browser this is natural model for the database access interaction we're after-users can submit database key to the server and receive the corresponding record as reply page we'll go into cgi basics in depth later in this bookbut as first examplelet' start out with simple interactive example that requests and then echoes back user' name in web browser the first page in this interaction is just an input form produced by the html file shown in example - this html file is stored on the web server machineand it is transferred to the web browser running on the client machine upon request example - pp \preview\cgi html interactive page enter your namenotice how this html form names the script that will process its input on the server in its action attribute this page is requested by submitting its url (web addresswhen received by the web browser on the clientthe input form that this code produces is shown in figure - (in internet explorer herefigure - cgi html input form page when this input form is submitteda web server intercepts the request (more on the web server in momentand runs the python cgi script in example - like the step adding web interface
4,631
on the server machine to handle the inputs and generate reply to the browser on the client it uses the cgi module to parse the form' input and insert it into the html reply streamproperly escaped the cgi module gives us dictionary-like interface to form inputs sent by the browserand the html code that this script prints winds up rendering the next page on the client' browser in the cgi worldthe standard output stream is connected to the client through socket example - pp \preview\cgi-bin\cgi py #!/usr/bin/python import cgi form cgi fieldstorage(parse form data print('content-typetext/html\ 'hdr plus blank line print('reply page'html reply page if not 'userin formprint('who are you?'elseprint('hello % !cgi escape(form['user'value)and if all goes wellwe receive the reply page shown in figure - --essentiallyjust an echo of the data we entered in the input page the page in this figure is produced by the html printed by the python cgi script running on the server along the waythe user' name was transferred from client to server and back again--potentially across networks and miles this isn' much of websiteof coursebut the basic principles here applywhether you're just echoing inputs or doing full-blown -whatever figure - cgi py script reply page for input form if you have trouble getting this interaction to run on unix-like systemsyou may need to modify the path to your python in the #line at the top of the script file and make it executable with chmod commandbut this is dependent on your web server (againmore on the missing server piece in moment sneak preview
4,632
and tags of the static html file in example - are missing strictly speakingsuch tags should be printedbut web browsers don' mind the omissionsand this book' goal is not to teach legalistic htmlsee other resources for more on html guis versus the web before moving onit' worth taking moment to compare this basic cgi example with the simple gui of example - and figure - herewe're running scripts on server to generate html that is rendered in web browser in the guiwe make calls to build the display and respond to events within single process and on single machine the gui runs multiple layers of softwarebut not multiple programs by contrastthe cgi approach is much more distributed--the serverthe browserand possibly the cgi script itself run as separate programs that usually communicate over network because of such differencesthe standalone gui model may be simpler and more directthere is no intermediate serverreplies do not require invoking new programno html needs to be generatedand the full power of gui toolkit is at our disposal on the other handa web-based interface can be viewed in any browser on any computer and only requires python on the server machine and just to muddle the waters furthera gui can also employ python' standard library networking tools to fetch and display data from remote server (that' how web browsers do their work internally)and some newer frameworks such as flexsilverlightand pyjamas provide toolkits that support more full-featured user interfaces within web pages on the client (the rias mentioned earlier)albeit at some added cost in code complexity and software stack depth we'll revisit the trade-offs of the gui and cgi schemes later in this bookbecause it' major design choice today firstlet' preview handful of pragmatic issues related to cgi work before we apply it to our people database running web server of courseto run cgi scripts at allwe need web server that will serve up our html and launch our python scripts on request the server is required mediator between the browser and the cgi script if you don' have an account on machine that has such server availableyou'll want to run one of your own we could configure and run full production-level web server such as the open source apache system (whichby the waycan be tailored with python-specific support by the mod_python extensionfor this howeveri instead wrote simple web server in python using the code in example - we'll revisit the tools used in this example later in this book in shortbecause python provides precoded support for various types of network serverswe can build step adding web interface
4,633
if we include comments and blank linesas we'll see later in this bookit' also easy to build proprietary network servers with low-level socket calls in pythonbut the standard library provides canned implementations for many common server typesweb based or otherwise the socketserver modulefor instancesupports threaded and forking versions of tcp and udp servers third-party systems such as twisted provide even more implementations for serving up web contentthe standard library modules used in example - provide what we need example - pp \preview\webserver py ""implement an http web server in python that knows how to run server-side cgi scripts coded in pythonserves files and scripts from current working dirpython scripts must be stored in webdir\cgi-bin or webdir\htbin""import ossys from http server import httpservercgihttprequesthandler webdir port where your html files and cgi-bin script directory live default os chdir(webdirrun in html root dir srvraddr (""portmy hostnameportnumber srvrobj httpserver(srvraddrcgihttprequesthandlersrvrobj serve_forever(run as perpetual daemon the classes this script uses assume that the html files to be served up reside in the current working directory and that the cgi scripts to be run live in cgi-bin or htbin subdirectory there we're using cgi-bin subdirectory for scriptsas suggested by the filename of example - some web servers look at filename extensions to detect cgi scriptsour script uses this subdirectory-based scheme instead to launch the serversimply run this script (in console windowby an icon clickor otherwise)it runs perpetuallywaiting for requests to be submitted from browsers and other clients the server listens for requests on the machine on which it runs and on the standard http port number to use this script to serve up other websiteseither launch it from the directory that contains your html files and cgi-bin subdirectory that contains your cgi scriptsor change its webdir variable to reflect the site' root directory (it will automatically change to that directory and serve files located therebut where in cyberspace do you actually run the server scriptif you look closely enoughyou'll notice that the server name in the addresses of the prior section' examples (near the top right of the browser after the this simplei am running the web server on the same machine as the web browserthat' what the server name "localhost(and the equivalent ip address "means that isthe client and server machines are the samethe client (web browser sneak preview
4,634
same computer though not meant for enterprise-level workthis turns out to be great way to test cgi scripts--you can develop them on the same machine without having to transfer code back to remote server machine after each change simply run this script from the directory that contains both your html files and cgi-bin subdirectory for scripts and then use here is the trace output the web server script produces in windows console window that is running on the same machine as the web browser and launched from the directory where the html files reside\pp \previewpython webserver py mark-vaio [ /jan/ : : "get /cgi html http/ mark-vaio [ /jan/ : : "post /cgi-bin/cgi py http/ mark-vaio [ /jan/ : : commandc:\python \python exe - :\users \mark\stuff\books\ \pp \dev\examples\pp \preview\cgi-bin\cgi py "mark-vaio [ /jan/ : : cgi script exited ok mark-vaio [ /jan/ : : "get /cgi-bin/cgi py?user=sue+smith http / mark-vaio [ /jan/ : : commandc:\python \python exe - :\users \mark\stuff\books\ \pp \dev\examples\pp \preview\cgi-bin\cgi py mark-vaio [ /jan/ : : cgi script exited ok one pragmatic note hereyou may need administrator privileges in order to run server on the script' default port on some platformseither find out how to run this way or try running on different port to run this server on different portchange the port number in the script and name it explicitly in the url ( we'll learn more about this convention later in this book and to run this server on remote computerupload the html files and cgi scripts subdirectory to the remote computerlaunch the server script on that machineand replace "localhostin the urls with the domain name or ip address of your server machine ( interaction will be as shown herebut inputs and replies will be automatically shipped across network connectionsnot routed between programs running on the same computer to delve further into the server classes our web server script employssee their implementation in python' standard library ( :\python \lib for python )one of the major advantages of open source system like python is that we can always look under the hood this way in we'll expand example - to allow the directory name and port numbers to be passed in on the command line using query strings and urllib in the basic cgi example shown earlierwe ran the python script by filling out and submitting form that contained the name of the script reallyserver-side cgi scripts can be invoked in variety of ways--either by submitting an input form as shown so step adding web interface
4,635
at the end such an explicit url can be sent to server either inside or outside of browserin senseit bypasses the traditional input form page for instancefigure - shows the reply generated by the server after typing url of the following form in the address field at the top of the web browser (means space here)figure - cgi py reply to get-style query parameters the inputs hereknown as query parametersshow up at the end of the url after the ?they are not entered into form' input fields adding inputs to urls is sometimes called get request our original input form uses the post methodwhich instead ships inputs in separate step luckilypython cgi scripts don' have to distinguish between the twothe cgi module' input parser handles any data submission method differences for us it' even possibleand often usefulto submit urls with inputs appended as query parameters completely outside any web browser the python urllib module packagefor instanceallows us to read the reply generated by server for any valid url in effectit allows us to visit web page or invoke cgi script from within another scriptyour python codeinstead of browseracts as the web client here is this module in actionrun from the interactive command linefrom urllib request import urlopen conn urlopen(reply conn read(reply 'reply page\nhello sue smith!\nurlopen(' 'reply page\nwho are you?\nurlopen(' 'reply page\nhello bob!\ sneak preview
4,636
notice that the output we read from the server is raw html code (normally rendered by browserwe can process this text with any of python' text-processing toolsincludingstring methods to search and split the re regular expression pattern-matching module full-blown html and xml parsing support in the standard libraryincluding html parseras well as sax-dom-and elementtree-style xml parsing tools when combined with such toolsthe urllib package is natural for variety of techniques--ad-hoc interactive testing of websitescustom client-side guis"screen scrapingof web page contentand automated regression testing systems for remote server-side cgi scripts formatting reply text one last fine pointbecause cgi scripts use text to communicate with clientsthey need to format their replies according to set of rules for instancenotice how example - adds blank line between the reply' header and its html by printing an explicit newline (\nin addition to the one print adds automaticallythis is required separator also note how the text inserted into the html reply is run through the cgi escape ( html escape in python see the note under "python html and url escape toolson page calljust in case the input includes character that is special in html for examplefigure - shows the reply we receive for form input bob smith--the in the middle becomes </ &gtin the replyand so doesn' interfere with real html code (use your browser' view source option to see this for yourself)if not escapedthe rest of the name would not be italicized figure - escaping html characters step adding web interface
4,637
content isn' knownscripts that generate html have to respect its rules as we'll see later in this booka related callurllib parse quoteapplies url escaping rules to text as we'll also seelarger frameworks often handle text formatting tasks for us web-based shelve interface nowto use the cgi techniques of the prior sections for our database applicationwe basically just need bigger input and reply form figure - shows the form we'll implement for accessing our database in web browser figure - peoplecgi html input page coding the website to implement the interactionwe'll code an initial html input formas well as python cgi script for displaying fetch results and processing update requests example - shows the input form' html code that builds the page in figure - example - pp \preview\peoplecgi html people input form key name age job pay sneak preview
4,638
to handle form (and otherrequestsexample - implements python cgi script that fetches and updates our shelve' records it echoes back page similar to that produced by example - but with the form fields filled in from the attributes of actual class objects in the shelve database as in the guithe same web page is used for both displaying results and inputting updates unlike the guithis script is run anew for each step of user interactionand it reopens the database each time (the reply page' action field provides link back to the script for the next requestthe basic cgi model provides no automatic memory from page to pageso we have to start from scratch each time example - pp \preview\cgi-bin\peoplecgi py ""implement web-based interface for viewing and updating class instances stored in shelvethe shelve lives on server (same machine if localhost""import cgishelvesysos shelvename 'class-shelvefieldnames ('name''age''job''pay'cgi test(dumps inputs shelve files are in cwd form cgi fieldstorage(print('content-typetext/html'sys path insert( os getcwd()parse form data hdrblank line is in replyhtml so this and pickler find person main html template replyhtml ""people input form key $rows""insert html for data rows at $rowsrowhtml '% \nrowshtml 'for fieldname in fieldnamesrowshtml +(rowhtml ((fieldname, )step adding web interface
4,639
def htmlize(adict)new adict copy(for field in fieldnamesvalue new[fieldnew[fieldcgi escape(repr(value)return new def fetchrecord(dbform)trykey form['key'value record db[keyfields record __dict__ fields['key'key exceptfields dict fromkeys(fieldnames'?'fields['key''missing or invalid key!return fields values may have &>etc display as codequoted html-escape special chars use attribute dict to fill reply string def updaterecord(dbform)if not 'keyin formfields dict fromkeys(fieldnames'?'fields['key''missing key input!elsekey form['key'value if key in dbrecord db[keyupdate existing record elsefrom person import person make/store new one for key record person(name='?'age='?'evalstrings must be quoted for field in fieldnamessetattr(recordfieldeval(form[fieldvalue)db[keyrecord fields record __dict__ fields['key'key return fields db shelve open(shelvenameaction form['action'value if 'actionin form else none if action ='fetch'fields fetchrecord(dbformelif action ='update'fields updaterecord(dbformelsefields dict fromkeys(fieldnames'?'bad submit button value fields['key''missing or invalid action!db close(print(replyhtml htmlize(fields)fill reply from dict this is fairly large scriptbecause it has to handle user inputsinterface with the databaseand generate html for the reply page its behavior is fairly straightforwardthoughand similar to the gui of the prior section sneak preview
4,640
few fine points before we move on first of allmake sure the web server script we wrote earlier in example - is running before you proceedit' going to catch our requests and route them to our script also notice how this script adds the current working directory (os getcwdto the sys path module search path when it first starts barring pythonpath changethis is required to allow both the pickler and this script itself to import the person module one level up from the script because of the new way the web server runs cgi scripts in python the current working directory isn' added to sys patheven though the shelve' files are located there correctly when opened such details can vary per server the only other feat of semi-magic the cgi script relies on is using record' attribute dictionary (__dict__as the source of values when applying html escapes to field values and string formatting to the html reply template string in the last line of the script recall that %(key)code replacement target fetches value by key from dictionaryd {'say' 'get''shrubbery' ['say' '%(say) =%(get)sd ' =shrubberyby using an object' attribute dictionarywe can refer to attributes by name in the format string in factpart of the reply template is generated by code if its structure is confusingsimply insert statements to print replyhtml and to call sys exitand run from simple command line this is how the table' html in the middle of the reply is generated (slightly formatted here for readability)key name age job pay this text is then filled in with key values from the record' attribute dictionary by string formatting at the end of the script this is done after running the dictionary through utility to convert its values to code text with repr and escape that text per html conventions with cgi escape (againthe last step isn' always requiredbut it' generally good practicethese html reply lines could have been hardcoded in the scriptbut generating them from tuple of field names is more general approach--we can add new fields in the future without having to update the html template each time python' string processing tools make this snap step adding web interface
4,641
could achieve much the same effect as the traditional format expression used by this scriptand it provides specific syntax for referencing object attributes which to some might seem more explicit than using __dict__ keysd {'say' 'get''shrubbery''%(say) =%(get)sd ' =shrubbery'{say={get}format(** ' =shrubberyexpressionkey reference methodkey reference from person import person bob person('bob' '%(name) %(age)sbob __dict__ 'bob '{ name={ age}format(bob'bob = expression__dict__ keys methodattribute syntax because we need to escape attribute values firstthoughthe format method call' attribute syntax can' be used directly this waythe choice is really between both technique' key reference syntax above (at this writingit' not clear which formatting technique may come to dominateso we take liberties with using either in this bookif one replaces the other altogether somedayyou'll want to go with the winner in the interest of securityi also need to remind you one last time that the eval call used in this script to convert inputs to python objects is powerfulbut not secure--it happily runs any python codewhich can perform any system modifications that the script' process has permission to make if you careyou'll need to trust the input sourcerun in restricted environmentor use more focused input converters like int and float this is generally larger concern in the web worldwhere request strings might arrive from arbitrary sources since we're all friends herethoughwe'll ignore the threat using the website despite the extra complexities of serversdirectoriesand stringsusing the web interface is as simple as using the guiand it has the added advantage of running on any machine with browser and web connection to fetch recordfill in the key field and click fetchthe script populates the page with field data grabbed from the corresponding class instance in the shelveas illustrated in figure - for key bob figure - shows what happens when the key comes from the posted form as usualyou can also invoke the cgi script by instead passing inputs on query string at the end of the urlfigure - shows the reply we get when accessing url of the following form sneak preview
4,642
figure - peoplecgi py reply for query parameters as we've seensuch url can be submitted either within your browser or by scripts that use tools such as the urllib package againreplace "localhostwith your server' domain name if you are running the script on remote machine to update recordfetch it by keyenter new values in the field inputsand click updatethe script will take the input fields and store them in the attributes of the class instance in the shelve figure - shows the reply we get after updating sue step adding web interface
4,643
and click updatethe cgi script creates new class instancefills out its attributesand stores it in the shelve under the new key there really is class object behind the web page herebut we don' have to deal with the logic used to generate it figure - shows record added to the database in this way figure - peoplecgi py update reply figure - peoplecgi py after adding new record in principlewe could also update and add records by submitting url--either from browser or from script--such aspeoplecgi py?action=update&key=sue&pay= &name=sue+smithmore sneak preview
4,644
difficult than filling out the input page here is part of the reply page generated for the "guidorecord' display of figure - (use your browser' "view page sourceoption to see this for yourselfnote how the characters are translated to html escapes with cgi escape before being inserted into the replykey name age job pay as usualthe standard library urllib module package comes in handy for testing our cgi scriptthe output we get back is raw htmlbut we can parse it with other standard library tools and use it as the basis of server-side script regression testing system run on any internet-capable machine we might even parse the server' reply fetched this way and display its data in client-side gui coded with tkinterguis and web pages are not mutually exclusive techniques the last test in the following interaction shows portion of the error message page' html that is produced when the action is missing or invalid in the inputswith line breaks added for readabilityfrom urllib request import urlopen url urlopen(urlread( '\npeople input form\ \ \ \ key\ name\ < more deleted urlopen(' '\npeople input form\ \ \ \ key\ name\ age\ more deleted in factif you're running this cgi script on "localhost,you can use both the last section' gui and this section' web interface to view the same physical shelve file-these are just alternative interfaces to the same persistent python objects for comparisonfigure - shows what the record we saw in figure - looks like in the guiit' the same objectbut we are not contacting an intermediate serverstarting other scriptsor generating html to view it and as beforewe can always check our work on the server machine either interactively or by running scripts we may be viewing database through web browsers and guisbutultimatelyit is just python objects in python shelve fileimport shelve db shelve open('class-shelve'db['sue'name 'sue smithstep adding web interface
4,645
db['guido'job 'bdfllist(db['guido'name[' '' '' 'list(db keys()['sue''bill''nobody''tomtom''tom''bob''peg''guido'here in action again is the original database script we wrote in example - before we moved on to guis and the webthere are many ways to view python data\pp \previewdump_db_classes py sue =sue smith bill =bill nobody =john doh none tomtom =tom tom tom =tom doe bob =bob smith peg = guido =gvr smith doe future directions naturallythere are plenty of improvements we could make heretoothe html code of the initial input page in example - for instanceis somewhat redundant with the script in example - and it could be automatically generated by another script that shares common information sneak preview
4,646
of the html generator tools we'll meet laterincluding htmlgen ( system for creating html from document object treesand psp (python server pagesa server-side html templating system for python similar to php and aspfor ease of maintenanceit might also be better to split the cgi script' html code off to separate file in order to better divide display from logic (different parties with possibly different skill sets could work on the different filesmoreoverif this website might be accessed by many people simultaneouslywe would have to add file locking or move to database such as zodb or mysql to support concurrent updates zodb and other full-blown database systems would also provide transaction rollbacks in the event of failures for basic file lockingthe os open call and its flags provide the tools we need orms (object relational mappersfor python such as sqlobject and sqlalchemy mentioned earlier might also allow us to gain concurrent update support of an underlying relational database systembut retain our python class view of the data in the endif our site grows much beyond few interactive pageswe might also migrate from basic cgi scripting to more complete web framework such as one of those mentioned at the start of this section-djangoturbogearspyjamasand others if we must retain information across pagestools such as cookieshidden inputsmod_python session dataand fastcgi may help too if our site eventually includes content produced by its own userswe might transition to plonea popular open source pythonand zope-based site builder thatusing workflow modeldelegates control of site content to its producers and if wireless or cloud interfaces are on our agendawe might eventually migrate our system to cell phones using python port such as those available for scripting nokia platforms and google' androidor to cloud-computing platform such as google' python-friendly app engine python tends to go wherever technology trends lead for nowthoughboth the gui and web-based interfaces we've coded get the job done the end of the demo and that concludes our sneak preview demo of python in action we've explored data representationoopobject persistenceguisand website basics we haven' studied any of these topics in any great depth hopefullythoughthis has piqued your curiosity about python applications programming in the rest of this bookwe'll delve into these and other application programming tools and topicsin order to help you put python to work in your own programs in the next we begin our tour with the systems programming and administration tools available to python programmers the end of the demo
4,647
've been involved with python for some years now as of this writing in and have seen it grow from an obscure language into one that is used in some fashion in almost every development organization and solid member of the top four or five most widely-used programming languages in the world it has been fun ride but looking back over the yearsit seems to me that if python truly has single legacyit is simply that python has made quality more central focus in the development world it was almost inevitable language that requires its users to line up code for readability can' help but make people raise questions about good software practice in general probably nothing summarizes this aspect of python life better than the standard library this module-- sort of easter egg in python written by python core developer tim peterswhich captures much of the design philosophy behind the language to see this for yourselfgo to any python interactive prompt and import the module (naturallyit' available on all platforms)import this the zen of pythonby tim peters beautiful is better than ugly explicit is better than implicit simple is better than complex complex is better than complicated flat is better than nested sparse is better than dense readability counts special cases aren' special enough to break the rules although practicality beats purity errors should never pass silently unless explicitly silenced in the face of ambiguityrefuse the temptation to guess there should be one-and preferably only one --obvious way to do it although that way may not be obvious at first unless you're dutch now is better than never although never is often better than *rightnow if the implementation is hard to explainit' bad idea if the implementation is easy to explainit may be good idea namespaces are one honking great idea -let' do more of thoseworth special mentionthe "explicit is better than implicitrule has become known as "eibtiin the python world--one of python' defining ideasand one of its sharpest contrasts with other languages as anyone who has worked in this field for more than few years can attestmagic and engineering do not mix python has not always followed all of these guidelinesof coursebut it comes very close and if python' main contribution to the software world is getting people to think about such thingsit seems like win besidesit looked great on the -shirt sneak preview
4,648
system programming this first in-depth part of the book presents python' system programming tools-interfaces to services in the underlying operating system as well as the context of an executing program it consists of the following this provides comprehensive first look at commonly used system interface tools it starts slowly and is meant in part as reference for tools and techniques we'll be using later in the book this continues the tour begun in by showing how python' system interfaces are applied to process standard streamscommand-line argumentsshell variablesand more this continues our survey of system interfaces by focusing on tools and techniques used to process files and directories in python we'll learn about binary filestree walkersand so on this is an introduction to python' library support for running programs in parallel hereyou'll find coverage of threadsprocess forkspipessocketssignalsqueuesand the like this last is collection of typical system programming examples that draw upon the material of the prior four python scripts here perform real tasksamong other thingsthey split and join filescompare and copy directory treestest other programsand search and launch files although this part of the book emphasizes systems programming tasksthe tools introduced are general-purpose and are used often in later
4,649
system tools "the os path to knowledgethis begins our in-depth look at ways to apply python to real programming tasks in this and the following you'll see how to use python to write system toolsguisdatabase applicationsinternet scriptswebsitesand more along the waywe'll also study larger python programming concepts in actioncode reusemaintainabilityobject-oriented programming (oop)and so on in this first part of the bookwe begin our python programming tour by exploring the systems application domain--scripts that deal with filesprogramsand the general environment surrounding program although the examples in this domain focus on particular kinds of tasksthe techniques they employ will prove to be useful in later parts of the book as well in other wordsyou should begin your journey hereunless you are already python systems programming wizard why python herepython' system interfaces span application domainsbut for the next five most of our examples fall into the category of system tools--programs sometimes called command-line utilitiesshell scriptssystem administrationsystems programmingand other permutations of such words regardless of their titleyou are probably already familiar with this sort of scriptthese scripts accomplish such tasks as processing files in directorylaunching test programsand so on such programs historically have been written in nonportable and syntactically obscure shell languages such as dos batch filescshand awk even in this relatively simple domainthoughsome of python' better attributes shine brightly for instancepython' ease of use and extensive built-in library make it simple (and even funto use advanced system tools such as threadssignalsforkssocketsand their kinsuch tools are much less accessible under the obscure syntax of shell languages and the slow development cycles of compiled languages python' support for concepts like code clarity and oop also help us write shell tools that can be read
4,650
from scratch moreoverwe'll find that python not only includes all the interfaces we need in order to write system toolsbut it also fosters script portability by employing python' standard librarymost system scripts written in python are automatically portable to all major platforms for instanceyou can usually run in linux python directory-processing script written in windows without changing its source code at all--simply copy over the source code though writing scripts that achieve such portability utopia requires some extra effort and practiceif used wellpython could be the only system scripting tool you need to use the next five to make this part of the book easier to studyi have broken it down into five in this 'll introduce the main system-related modules in overview fashion we'll meet some of the most commonly used system tools here for the first time in we continue exploring the basic system interfaces by studying their role in core system programming conceptsstreamscommand-line argumentsenvironment variablesand so on focuses on the tools python provides for processing filesdirectoriesand directory trees in we'll move on to cover python' standard tools for parallel processing--processesthreadsqueuespipessignalsand more wraps up by presenting collection of complete system-oriented programs the examples here are larger and more realisticand they use the tools introduced in the prior four to perform realpractical tasks this collection includes both general system scriptsas well as scripts for processing directories of files especially in the examples at the end of this partwe will be concerned as much with system interfaces as with general python development concepts we'll see nonobject-oriented and object-oriented versions of some examples along the wayfor instanceto help illustrate the benefits of thinking in more strategic ways "batteries includedthis and those that followdeal with both the python language and its standard library-- collection of precoded modules written in python and that are automatically installed with the python interpreter although python itself provides an easy-touse scripting languagemuch of the real action in python development involves this vast library of programming tools ( few hundred modules at last countthat ship with the python package system tools
4,651
described as batteries included-- phrase generally credited to frank stajano meaning that most of what you need for real day-to-day work is already there for importing python' standard librarywhile not part of the core language per seis standard part of the python system and you can expect it to be available wherever your scripts run indeedthis is noteworthy difference between python and some other scripting languages--because python comes with so many library tools "out of the box,supplemental sites like perl' cpan are not as important as we'll seethe standard library forms much of the challenge in python programming once you've mastered the core languageyou'll find that you'll spend most of your time applying the built-in functions and modules that come with the system on the other handlibraries are where most of the fun happens in practiceprograms become most interesting when they start using services external to the language interpreternetworksfilesguisxmldatabasesand so on all of these are supported in the python standard library beyond the standard librarythere is an additional collection of third-party packages for python that must be fetched and installed separately as of this writingyou can find most of these third-party extensions via general web searchesand using the links at orgsome third-party extensions are large systems in their own rightnumpydjangoand vpythonfor instanceadd vector processingwebsite constructionand visualizationrespectively if you have to do something special with pythonchances are good that either its support is part of the standard python install package or you can find free and open source module that will help most of the tools we'll employ in this text are standard part of pythonbut 'll be careful to point out things that must be installed separately of coursepython' extreme code reuse idiom also makes your programs dependent on the code you reusein practicethoughand as we'll see repeatedly in this bookpowerful libraries coupled with open source access speed development without locking you into an existing set of features or limitations system scripting overview to begin our exploration of the systems domainwe will take quick tour through the standard library sys and os modules in this before moving on to larger system programming concepts as you can tell from the length of their attribute listsboth of these are large modules--the following reflects python running on windows outside idlec:\pp \systempython python ( : aug : : [msc bit )on win type "help""copyright""creditsor "licensefor more information import sysos len(dir(sys) attributes system scripting overview
4,652
len(dir(os path) on windowsmore on unix nested module within os the content of these two modules may vary per python version and platform for exampleos is much larger under cygwin after building python from its source code there (cygwin is system that provides unix-like functionality on windowsit is discussed further in "more on cygwin python for windowson page )/python exe python ( : feb : : [gcc (cygming specialgdc using dmd )on cygwin type "help""copyright""creditsor "licensefor more information import sysos len(dir(sys) len(dir(os) len(dir(os path) as ' not going to demonstrate every item in every built-in modulethe first thing want to do is show you how to get more details on your own officiallythis task also serves as an excuse for introducing few core system scripting conceptsalong the waywe'll code first script to format documentation python system modules most system-level interfaces in python are shipped in just two modulessys and os that' somewhat oversimplifiedother standard modules belong to this domain too among them are the followingglob for filename expansion socket for network connections and inter-process communication (ipcthreading_threadqueue for running and synchronizing concurrent threads timetimeit for accessing system time details subprocessmultiprocessing for launching and controlling parallel processes signalselectshutiltempfileand others for various other system-related tasks third-party extensions such as pyserial ( serial port interface)pexpect (an expect work-alike for controlling cross-program dialogs)and even twisted ( networking system tools
4,653
built-in functions are actually system interfaces as well--the open functionfor exampleinterfaces with the file system but by and largesys and os together form the core of python' built-in system tools arsenal in principle at leastsys exports components related to the python interpreter itself ( the module search path)and os contains variables and functions that map to the operating system on which python is run in practicethis distinction may not always seem clear-cut ( the standard input and output streams show up in sysbut they are arguably tied to operating system paradigmsthe good news is that you'll soon use the tools in these modules so often that their locations will be permanently stamped on your memory the os module also attempts to provide portable programming interface to the underlying operating systemits functions may be implemented differently on different platformsbut to python scriptsthey look the same everywhere and if that' still not enoughthe os module also exports nested submoduleos pathwhich provides portable interface to file and directory processing tools module documentation sources as you can probably deduce from the preceding paragraphslearning to write system scripts in python is mostly matter of learning about python' system modules luckilythere are variety of information sources to make this task easier--from module attributes to published references and books for instanceif you want to know everything that built-in module exportsyou can read its library manual entrystudy its source code (python is open source softwareafter all)or fetch its attribute list and documentation string interactively let' import sys in python and see what it has to offerc:\pp \systempython import sys dir(sys['__displayhook__''__doc__''__excepthook__''__name__''__package__''__stderr__''__stdin__''__stdout__''_clear_type_cache''_current_frames''_getframe''api_version''argv''builtin_module_names''byteorder''call_tracing''callstats''copyright''displayhook''dllhandle''dont_write_bytecode''exc_info''excepthook''exec_prefix''executable''exit''flags''float_info''float_repr_style''getcheckinterval''getdefaultencoding''getfilesystemencoding''getprofile''getrecursionlimit''getrefcount''getsizeof''gettrace''getwindowsversion''hexversion''int_info''intern''maxsize''maxunicode''meta_path''modules''path''path_hooks''path_importer_cache''platform''prefix''ps ''ps ''setcheckinterval''setfilesystemencoding''setprofile''setrecursionlimit'they may also work their way into your subconscious python newcomers sometimes describe phenomenon in which they "dream in python(insert overly simplistic freudian analysis here system scripting overview
4,654
'warnoptions''winver'the dir function simply returns list containing the string names of all the attributes in any object with attributesit' handy memory jogger for modules at the interactive prompt for examplewe know there is something called sys versionbecause the name version came back in the dir result if that' not enoughwe can always consult the __doc__ string of built-in modulessys __doc__ "this module provides access to some objects used or maintained by the\ninterpre ter and to functions that interact strongly with the interpreter \ \ndynamic obj ects:\ \nargv -command line argumentsargv[ is the script pathname if known \npath -module search pathpath[ is the script directoryelse ''\nmodules -dictionary of loaded modules\ \ndisplayhook -called to show results in an lots of text deleted here paging documentation strings the __doc__ built-in attribute just shown usually contains string of documentationbut it may look bit weird when displayed this way--it' one long string with embedded end-line characters that print as \nnot as nice list of lines to format these strings for more humane displayyou can simply use print function-call statementprint(sys __doc__this module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter dynamic objectsargv -command line argumentsargv[ is the script pathname if known path -module search pathpath[ is the script directoryelse 'modules -dictionary of loaded modules lots of lines deleted here the print built-in functionunlike interactive displaysinterprets end-line characters correctly unfortunatelyprint doesn'tby itselfdo anything about scrolling or paging and so can still be unwieldy on some platforms tools such as the built-in help function can do betterhelp(syshelp on built-in module sysname sys file (built-inmodule docs system tools
4,655
this module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter dynamic objectsargv -command line argumentsargv[ is the script pathname if known path -module search pathpath[ is the script directoryelse 'modules -dictionary of loaded modules lots of lines deleted here the help function is one interface provided by the pydoc system--standard library code that ships with python and renders documentation (documentation stringsas well as structural detailsrelated to an object in formatted way the format is either like unix manpagewhich we get for helpor an html pagewhich is more grandiose it' handy way to get basic information when working interactivelyand it' last resort before falling back on manuals and books custom paging script the help function we just met is also fairly fixed in the way it displays informationalthough it attempts to page the display in some contextsits page size isn' quite right on some of the machines use moreoverit doesn' page at all in the idle guiinstead relying on manual use if the scrollbar--potentially painful for large displays when want more control over the way help text is printedi usually use utility script of my ownlike the one in example - example - pp \system\more py ""split and interactively page string or file of text ""def more(textnumlines= )lines text splitlines(like split('\ 'but no 'at end while lineschunk lines[:numlineslines lines[numlines:for line in chunkprint(lineif lines and input('more?'not in [' '' ']break if __name__ ='__main__'import sys more(open(sys argv[ ]read() when runnot imported page contents of file on cmdline the meat of this file is its more functionand if you know enough python to be qualified to read this bookit should be fairly straightforward it simply splits up string around end-line charactersand then slices off and displays few lines at time ( by defaultto avoid scrolling off the screen slice expressionlines[: ]gets the first items in listand lines[ :gets the restto show different number of lines each timesystem scripting overview
4,656
the numlines argument of the more functionthe splitlines string object method call that this script employs returns list of substrings split at line ends ( ["line""line"]an alternative splitlines method does similar workbut retains an empty line at the end of the result if the last line is \ terminatedline 'aaa\nbbb\nccc\nline split('\ '['aaa''bbb''ccc'''line splitlines(['aaa''bbb''ccc'as we'll see more formally in the end-of-line character is normally always \ (which stands for byte usually having binary value of within python scriptno matter what platform it is run upon (if you don' already know why this mattersdos \ characters in text are dropped by default when read string method basics nowexample - is simple python programbut it already brings up three important topics that merit quick detours hereit uses string methodsreads from fileand is set up to be run or imported python string methods are not system-related tool per sebut they see action in most python programs in factthey are going to show up throughout this as well as those that followso here is quick review of some of the more useful tools in this set string methods include calls for searching and replacingmystr 'xxxspamxxxmystr find('spam' mystr 'xxaaxxaamystr replace('aa''spam''xxspamxxspamreturn first offset global replacement the find call returns the offset of the first occurrence of substringand replace does global search and replacement like all string operationsreplace returns new string instead of changing its subject in-place (recall that strings are immutablewith these methodssubstrings are just stringsin we'll also meet module called re that allows regular expression patterns to show up in searches and replacements in more recent pythonsthe in membership operator can often be used as an alternative to find if all we need is yes/no answer (it tests for substring' presencethere are also handful of methods for removing whitespace on the ends of strings--especially useful for lines of text read from filemystr 'xxxspamxxx'spamin mystr system tools substring search/test
4,657
'niin mystr false mystr find('ni'- mystr '\ ni\nmystr strip('nimystr rstrip('\ niwhen not found remove whitespace samebut just on right side string methods also provide functions that are useful for things such as case conversionsand standard library module named string defines some useful preset variablesamong other thingsmystr 'shrubberymystr lower('shrubberycase converters mystr isalpha(true mystr isdigit(false content tests import string string ascii_lowercase 'abcdefghijklmnopqrstuvwxyzcase presetsfor 'in'etc string whitespace \ \ \ \ \ cwhitespace characters there are also methods for splitting up strings around substring delimiter and putting them back together with substring in between we'll explore these tools later in this bookbut as an introductionhere they are at workmystr 'aaa,bbb,cccmystr split(','['aaa''bbb''ccc'split into substrings list mystr ' \nc\ndmystr split([' '' '' '' 'default delimiterwhitespace delim 'nidelim join(['aaa''bbb''ccc']'aaanibbbnicccjoin substrings list join([' ''dead''parrot']' dead parrotadd space between system scripting overview
4,658
chars [' '' '' '' '' '' '' 'chars append('!''join(chars'lorreta!convert to characters list to stringempty delimiter these calls turn out to be surprisingly powerful for examplea line of data columns separated by tabs can be parsed into its columns with single split callthe more py script uses the splitlines variant shown earlier to split string into list of line strings in factwe can emulate the replace call we saw earlier in this section with split/join combinationmystr 'xxaaxxaa'spamjoin(mystr split('aa')'xxspamxxspamstr replacethe hard wayfor future referencealso keep in mind that python doesn' automatically convert strings to numbersor vice versaif you want to use one as you would use the otheryou must say so with manual conversionsint(" ")eval(" "( string to int conversions str( )repr( (' '' 'int to string conversions ("% )'{: }format( (' '' 'via formatting expressionmethod " str( )int(" " (' ' concatenationaddition in the last command herethe first expression triggers string concatenation (since both sides are strings)and the second invokes integer addition (because both objects are numberspython doesn' assume you meant one or the other and convert automaticallyas rule of thumbpython tries to avoid magic--and the temptation to guess-whenever possible string tools will be covered in more detail later in this book (in factthey get full in part )but be sure to also see the library manual for additional string method tools other string concepts in python xunicode and bytes technically speakingthe python string story is bit richer than 've implied here what 've shown so far is the str object type-- sequence of characters (technicallyunicode "code pointsrepresented as unicode "code units"which represents both ascii and wider unicode textand handles encoding and decoding both manually on request and automatically on file transfers strings are coded in quotes ( 'abc')along with various syntax for coding non-ascii text ( '\xc \xe ''\ \ ' system tools
4,659
bytearray-- mutable variant of bytes you generally know you are dealing with bytes if strings display or are coded with leading "bcharacter before the opening quote ( 'abc' '\xc \xe 'as we'll see in files in follow similar dichotomyusing str in text mode (which also handles unicode encodings and lineend conversionsand bytes in binary mode (which transfers bytes to and from files unchangedand in we'll see the same distinction for tools like socketswhich deal in byte strings today unicode text is used in internationalized applicationsand many of python' binaryoriented tools deal in byte strings today this includes some file tools we'll meet along the waysuch as the open calland the os listdir and os walk tools we'll study in upcoming as we'll seeeven simple directory tools sometimes have to be aware of unicode in file content and names moreovertools such as object pickling and binary data parsing are byte-oriented today later in the bookwe'll also find that unicode also pops up today in the text displayed in guisthe bytes shipped other networksinternet standard such as emailand even some persistence topics such as dbm files and shelves any interface that deals in text necessarily deals in unicode todaybecause str is unicodewhether ascii or wider once we reach the realm of the applications programming presented in this bookunicode is no longer an optional topic for most python programmers in this bookwe'll defer further coverage of unicode until we can see it in the context of application topics and practical programs for more fundamental details on how ' unicode text and binary data support impact both string and file usage in some rolesplease see learning pythonfourth editionsince this is officially core language topicit enjoys in-depth coverage and full -page dedicated in that book file operation basics besides processing stringsthe more py script also uses files--it opens the external file whose name is listed on the command line using the built-in open functionand it reads that file' text into memory all at once with the file object read method since file objects returned by open are part of the core python language itselfi assume that you have at least passing familiarity with them at this point in the text but just in case you've flipped to this early on in your pythonhoodthe following calls load file' contents into stringload fixed-size set of bytes into stringload file' contents into list of line stringsand load the next line in the file into stringrespectivelyopen('file'read(open('file'read(nopen('file'readlines(open('file'readline(read entire file into string read next bytes into string read entire file into line strings list read next linethrough '\nsystem scripting overview
4,660
to read their output file objects also have write methods for sending strings to the associated file file-related topics are covered in depth in but making an output file and reading it back is easy in pythonfile open('spam txt'' 'file write(('spam '\ ' file close(create file spam txt write textreturns #characters written file open('spam txt'text file read(text 'spamspamspamspamspam\nor open('spam txt'read(read into string using programs in two ways also by way of reviewthe last few lines in the more py file in example - introduce one of the first big concepts in shell tool programming they instrument the file to be used in either of two ways--as script or as library recall that every python module has built-in __name__ variable that python sets to the __main__ string only when the file is run as programnot when it' imported as library because of thatthe more function in this file is executed automatically by the last line in the file when this script is run as top-level programbut not when it is imported elsewhere this simple trick turns out to be one key to writing reusable script codeby coding program logic as functions rather than as top-level codeyou can also import and reuse it in other scripts the upshot is that we can run more py by itself or import and call its more function elsewhere when running the file as top-level programwe list on the command line the name of file to be read and pagedas 'll describe in more depth in the next words typed in the command that is used to start program show up in the built-in sys argv list in python for examplehere is the script file in actionpaging itself (be sure to type this command line in your pp \system directoryor it won' find the input filemore on command lines later) :\pp \systempython more py more py ""split and interactively page string or file of text ""def more(textnumlines= )lines text splitlines(like split('\ 'but no 'at end while lineschunk lines[:numlineslines lines[numlines:for line in chunkprint(linemore? if lines and input('more?'not in [' '' ']break system tools
4,661
import sys more(open(sys argv[ ]read() when runnot imported page contents of file on cmdline when the more py file is importedwe pass an explicit string to its more functionand this is exactly the sort of utility we need for documentation text running this utility on the sys module' documentation string gives us bit more information in humanreadable form about what' available to scriptsc:\pp \systempython from more import more import sys more(sys __doc__this module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter dynamic objectsargv -command line argumentsargv[ is the script pathname if known path -module search pathpath[ is the script directoryelse 'modules -dictionary of loaded modules displayhook -called to show results in an interactive session excepthook -called to handle any uncaught exception other than systemexit to customize printing in an interactive session or to install custom top-level exception handlerassign other functions to replace these stdin -standard input file objectused by input(morepressing "yor "yhere makes the function display the next few lines of documentationand then prompt againunless you've run past the end of the lines list try this on your own machine to see what the rest of the module' documentation string looks like also try experimenting by passing different window size in the second argument--more(sys __doc__ shows just lines at time python library manuals if that still isn' enough detailyour next step is to read the python library manual' entry for sys to get the full story all of python' standard manuals are available onlineand they often install alongside python itself on windowsthe standard manuals are installed automaticallybut here are few simple pointerson windowsclick the start buttonpick all programsselect the python entry thereand then choose the python manuals item the manuals should magically appear on your displayas of python the manuals are provided as windows help file and so support searching and navigation on linux or mac os xyou may be able to click on the manualsentries in file explorer or start your browser from shell command line and navigate to the library manual' html files on your machine system scripting overview
4,662
go to python' website at links there this website also has simple searching utility for the manuals however you get startedbe sure to pick the library manual for things such as systhis manual documents all of the standard librarybuilt-in types and functionsand more python' standard manual set also includes short tutoriala language referenceextending referencesand more commercially published references at the risk of sounding like marketing droidi should mention that you can also purchase the python manual setprinted and boundsee the book information page at books are also available todayincluding python essential referencepython in nutshellpython standard libraryand python pocket reference some of these books are more complete and come with examplesbut the last one serves as convenient memory jogger once you've taken library tour or two introducing the sys module but enough about documentation sources (and scripting basics)--let' move on to system module details as mentioned earlierthe sys and os modules form the core of much of python' system-related tool set to see howwe'll turn to quickinteractive tour through some of the tools in these two modules before applying them in bigger examples we'll start with systhe smaller of the tworemember that to see full list of all the attributes in sysyou need to pass it to the dir function (or see where we did so earlier in this platforms and versions like most modulessys includes both informational names and functions that take action for instanceits attributes give us the name of the underlying operating system on which the platform code is runningthe largest possible "natively sizedinteger on this machine (though integers can be arbitrarily long in python )and the version number of the python interpreter running our codec:\pp \systempython import sys full disclosurei also wrote the last of the books listed as replacement for the reference appendix that appeared in the first edition of this bookit' meant to be supplement to the text you're readingand its latest edition also serves as translation resource for python readers as explained in the prefacethe book you're holding is meant as tutorialnot referenceso you'll probably want to find some sort of reference resource eventually (though ' nearly narcissistic enough to require that it be mine system tools
4,663
('win ' ( : aug : : more deleted 'if sys platform[: ='win'print('hello windows'hello windows if you have code that must act differently on different machinessimply test the sys platform string as done herealthough most of python is cross-platformnonportable tools are usually wrapped in if tests like the one here for instancewe'll see later that some program launch and low-level console interaction tools may vary per platform--simply test sys platform to pick the right tool for the machine on which your script is running the module search path the sys module also lets us inspect the module search path both interactively and within python program sys path is list of directory name strings representing the true search path in running python interpreter when module is importedpython scans this list from left to rightsearching for the module' file on each directory named in the list because of thatthis is the place to look to verify that your search path is really set as intended +the sys path list is simply initialized from your pythonpath setting--the content of any pth path files located in python' directories on your machine plus system defaults--when the interpreter is first started up in factif you inspect sys path interactivelyyou'll notice quite few directories that are not on your pythonpathsys path also includes an indicator for the script' home directory (an empty string-something 'll explain in more detail after we meet os getcwdand set of standard library directories that may vary per installationsys path [''' :\\pp thed\\examples'plus standard library paths deleted surprisinglysys path can actually be changed by programtoo script can use list operations such as appendextendinsertpopand removeas well as the del statement to configure the search path at runtime to include all the source directories to which it needs access python always uses the current sys path setting to importno matter what you've changed it tosys path append( ' :\mydir'sys path [''' :\\pp thed\\examples'more deleted ' :\\mydir'+it' not impossible that python sees pythonpath differently than you do syntax error in your system shell configuration files may botch the setting of pythonpatheven if it looks fine to you on windowsfor exampleif space appears around the of dos set command in your configuration file ( set name value)you may actually set name to an empty stringnot to valueintroducing the sys module
4,664
variablebut not very permanent one changes to sys path are retained only until the python process endsand they must be remade every time you start new python program or session howeversome types of programs ( scripts that run on web servermay not be able to depend on pythonpath settingssuch scripts can instead configure sys path on startup to include all the directories from which they will need to import modules for more concrete use casesee example - in the prior -there we had to tweak the search path dynamically this waybecause the web server violated our import path assumptions windows directory paths notice the use of raw string literal in the sys path configuration codebecause backslashes normally introduce escape code sequences in python stringswindows users should be sure to either double up on backslashes when using them in dos directory path strings ( in " :\\dir"\is an escape sequence that really means \)or use raw string constants to retain backslashes literally ( " :\dir"if you inspect directory paths on windows (as in the sys path interaction listing)python prints double \to mean single technicallyyou can get away with single in string if it is followed by character python does not recognize as the rest of an escape sequencebut doubles and raw strings are usually easier than memorizing escape code tables also note that most python library calls accept either forward (/or backward (\slashes as directory path separatorsregardless of the underlying platform that isusually works on windows too and aids in making scripts portable to unix tools in the os and os path modulesdescribed later in this further aid in script path portability the loaded modules table the sys module also contains hooks into the interpretersys modulesfor exampleis dictionary containing one name:module entry for every module imported in your python session or program (reallyin the calling python process)sys modules {'reprlib'more deleted list(sys modules keys()['reprlib''heapq''__future__''sre_compile''_collections''locale''_sre''functools''encodings''site''operator''io''__main__'more deleted sys sys modules['sys' system tools
4,665
modules loaded by program (just iterate over the keys of sys modulesalso in the interpret hooks categoryan object' reference count is available via sys getrefcountand the names of modules built-in to the python executable are listed in sys builtin_module_names see python' library manual for detailsthese are mostly python internals informationbut such hooks can sometimes become important to programmers writing tools for other programmers to use exception details other attributes in the sys module allow us to fetch all the information related to the most recently raised python exception this is handy if we want to process exceptions in more generic fashion for instancethe sys exc_info function returns tuple with the latest exception' typevalueand traceback object in the all class-based exception model that python usesthe first two of these correspond to the most recently raised exception' classand the instance of it which was raisedtryraise indexerror exceptprint(sys exc_info()(indexerror()we might use such information to format our own error message to display in gui pop-up window or html web page (recall that by defaultuncaught exceptions terminate programs with python error displaythe first two items returned by this call have reasonable string displays when printed directlyand the third is traceback object that can be processed with the standard traceback moduleimport tracebacksys def grail( )raise typeerror('already got one'trygrail('arthur'exceptexc_info sys exc_info(print(exc_info[ ]print(exc_info[ ]traceback print_tb(exc_info[ ]already got one file ""line in file ""line in grail the traceback module can also format messages as strings and route them to specific file objectssee the python library manual for more details introducing the sys module
4,666
the sys module exports additional commonly-used tools that we will meet in the context of larger topics and examples introduced later in this part of the book for instancecommand-line arguments show up as list of strings called sys argv standard streams are available as sys stdinsys stdoutand sys stderr program exit can be forced with sys exit calls since these lead us to bigger topicsthoughwe will cover them in sections of their own introducing the os module as mentionedos is the larger of the two core system modules it contains all of the usual operating-system calls you use in programs and shell scripts its calls deal with directoriesprocessesshell variablesand the like technicallythis module provides posix tools-- portable standard for operating-system calls--along with platformindependent directory processing tools as the nested module os path operationallyos serves as largely portable interface to your computer' system callsscripts written with os and os path can usually be run unchanged on any platform on some platformsos includes extra tools available just for that platform ( low-level process calls on unix)by and largethoughit is as cross-platform as is technically feasible tools in the os module let' take quick look at the basic interfaces in os as previewtable - summarizes some of the most commonly used tools in the os moduleorganized by functional area table - commonly used os module tools tasks tools shell variables os environ running programs os systemos popenos execvos spawnv spawning processes os forkos pipeos waitpidos kill descriptor fileslocks os openos reados write file processing os removeos renameos mkfifoos mkdiros rmdir administrative tools os getcwdos chdiros chmodos getpidos listdiros access portability tools os sepos pathsepos curdiros path splitos path join pathname tools os path exists('path')os path isdir('path')os path getsize('path'if you inspect this module' attributes interactivelyyou get huge list of names that will vary per python releasewill likely vary per platformand isn' incredibly useful system tools
4,667
of this list to save space--run the command on your own)import os dir(os['f_ok''mutablemapping''o_append''o_binary''o_creat''o_excl''o_noinh erit''o_random''o_rdonly''o_rdwr''o_sequential''o_short_lived''o_tem porary''o_text''o_trunc''o_wronly''p_detach''p_nowait''p_nowaito'p_overlay''p_wait''r_ok''seek_cur''seek_end''seek_set''tmp_max' lines removed here 'pardir''path''pathsep''pipe''popen''putenv''read''remove''rem ovedirs''rename''renames''rmdir''sep''spawnl''spawnle''spawnv'' pawnve''startfile''stat''stat_float_times''stat_result''statvfs_result ''strerror''sys''system''times''umask''unlink''urandom''utime''waitpid''walk''write'besides all of thesethe nested os path module exports even more toolsmost of which are related to processing file and directory names portablydir(os path['__all__''__builtins__''__doc__''__file__''__name__''__package__''_get_altsep''_get_bothseps''_get_colon''_get_dot''_get_empty''_get_sep''_getfullpathname''abspath''altsep''basename''commonprefix''curdir''defpath''devnull''dirname''exists''expanduser''expandvars''extsep''genericpath''getatime''getctime''getmtime''getsize''isabs''isdir''isfile''islink''ismount''join''lexists''normcase''normpath''os''pardir''pathsep''realpath''relpath''sep''split''splitdrive''splitext''splitunc''stat''supports_unicode_filenames''sys'administrative tools just in case those massive listings aren' quite enough to go onlet' experiment interactively with some of the more commonly used os tools like systhe os module comes with collection of informational and administrative toolsos getpid( os getcwd(' :\\pp thed\\examples\\pp \\systemos chdir( ' :\users'os getcwd(' :\\usersas shown herethe os getpid function gives the calling process' process id ( unique system-defined identifier for running programuseful for process control and unique name creation)and os getcwd returns the current working directory the current working directory is where files opened by your script are assumed to liveunless their names include explicit directory paths that' why earlier told you to run the following command in the directory where more py livesc:\pp \systempython more py more py introducing the os module
4,668
you could add one to page files in another directoryif you need to run in different working directorycall the os chdir function to change to new directoryyour code will run relative to the new directory for the rest of the program (or until the next os chdir callthe next will have more to say about the notion of current working directoryand its relation to module imports when it explores script execution context portability constants the os module also exports set of names designed to make cross-platform programming simpler the set includes platform-specific settings for path and directory separator charactersparent and current directory indicatorsand the characters used to terminate lines on the underlying computer os pathsepos sepos pardiros curdiros linesep (';''\\''''\ \ 'os sep is whatever character is used to separate directory components on the platform on which python is runningit is automatically preset to on windowsfor posix machinesand on some macs similarlyos pathsep provides the character that separates directories on directory listsfor posix and for dos and windows by using such attributes when composing and decomposing system-related strings in our scriptswe make the scripts fully portable for instancea call of the form dir path split(os sepwill correctly split platform-specific directory names into componentsthough dirpath may look like dir\dir on windowsdir/dir on linuxand dir:dir on some macs as mentionedon windows you can usually use forward slashes rather than backward slashes when giving filenames to be openedbut these portability constants allow scripts to be platform neutral in directory processing code notice also how os linesep comes back as \ \ here--the symbolic escape code which reflects the carriage-return line-feed line terminator convention on windowswhich you don' normally notice when processing text files in python we'll learn more about end-of-line translations in common os path tools the nested module os path provides large set of directory-related tools of its own for exampleit includes portable functions for tasks such as checking file' type (isdirisfileand others)testing file existence (exists)and fetching the size of file by name (getsize)os path isdir( ' :\users')os path isfile( ' :\users'(truefalseos path isdir( ' :\config sys')os path isfile( ' :\config sys'(falsetrueos path isdir('nonesuch')os path isfile('nonesuch' system tools
4,669
os path exists( ' :\users\brian'false os path exists( ' :\users\default'true os path getsize( ' :\autoexec bat' the os path isdir and os path isfile calls tell us whether filename is directory or simple fileboth return false if the named file does not exist (that isnonexistence implies negationwe also get calls for splitting and joining directory path stringswhich automatically use the directory name conventions on the platform on which python is runningos path split( ' :\temp\data txt'(' :\\temp''data txt'os path join( ' :\temp''output txt'' :\\temp\\output txtname ' :\temp\data txtos path dirname(name)os path basename(name(' :\\temp''data txt'windows paths name '/home/lutz/temp/data txtos path dirname(name)os path basename(name('/home/lutz/temp''data txt'unix-style paths os path splitext( ' :\pp thed\examples\pp \pydemos pyw'(' :\\pp thed\\examples\\pp \\pydemos'pyw'os path split separates filename from its directory pathand os path join puts them back together--all in entirely portable fashion using the path conventions of the machine on which they are called the dirname and basename calls here return the first and second items returned by split simply as convenienceand splitext strips the file extension (after the last subtle pointit' almost equivalent to use string split and join method calls with the portable os sep stringbut not exactlyos sep '\\pathname ' :\pp thed\examples\pp \pydemos pywos path split(pathname(' :\\pp thed\\examples\\pp ''pydemos pyw'split file from dir pathname split(os sep[' :''pp thed''examples''pp ''pydemos pyw'split on every slash os sep join(pathname split(os sep)' :\\pp thed\\examples\\pp \\pydemos pywos path join(*pathname split(os sep)' :pp thed\\examples\\pp \\pydemos pywintroducing the os module
4,670
slash because of the windows drive syntaxuse the preceding str join method instead if the difference matters the normpath call comes in handy if your paths become jumble of unix and windows separatorsmixed ' :\\temp\\public/files/index htmlos path normpath(mixed' :\\temp\\public\\files\\index htmlprint(os path normpath( ' :\temp\\sub\file ext') :\temp\sub\file ext this module also has an abspath call that portably returns the full directory pathname of fileit accounts for adding the current directory as path prefixparent syntaxand moreos chdir( ' :\users'os getcwd(' :\\usersos path abspath(''' :\\usersos path abspath('temp'' :\\users\\tempos path abspath( 'pp \dev'' :\\users\\pp \\devempty string means the cwd expand to full pathname in cwd partial paths relative to cwd os path abspath('' :\\usersos path abspath('' :\\os path abspath( \examples'' :\\examplesrelative path syntax expanded os path abspath( ' :\pp thed\'' :\\pp thed\\os path abspath( ' :\temp\spam txt'' :\\temp\\spam txtabsolute paths unchanged because filenames are relative to the current working directory when they aren' fully specified pathsthe os path abspath function helps if you want to show users what directory is truly being used to store file on windowsfor examplewhen gui-based programs are launched by clicking on file explorer icons and desktop shortcutsthe execution directory of the program is the clicked file' home directorybut that is not always obvious to the person doing the clickingprinting file' abspath can help running shell commands from scripts the os module is also the place where we run shell commands from within python scripts this concept is intertwined with otherssuch as streamswhich we won' cover fully until the next but since this is key concept employed throughout this system tools
4,671
scripts to run any command line that you can type in console windowos system runs shell command from python script os popen runs shell command and connects to its input or output streams in additionthe relatively new subprocess module provides finer-grained control over streams of spawned shell commands and can be used as an alternative toand even for the implementation ofthe two calls above (albeit with some cost in extra code complexitywhat' shell commandto understand the scope of the calls listed abovewe first need to define few terms in this textthe term shell means the system that reads and runs command-line strings on your computerand shell command means command-line string that you would normally enter at your computer' shell prompt for exampleon windowsyou can start an ms-dos console window ( "command prompt"and type dos commands there--commands such as dir to get directory listingtype to view filenames of programs you wish to startand so on dos is the system shelland commands such as dir and type are shell commands on linux and mac os xyou can start new shell session by opening an xterm or terminal window and typing shell commands there too--ls to list directoriescat to view filesand so on variety of shells are available on unix ( cshksh)but they all read and run command lines here are two shell commands typed and run in an ms-dos console box on windowsc:\pp \systemdir / helloshell py more py more pyc spam txt __init__ py type shell command line its output shows up here dos is the shell on windows :\pp \systemtype helloshell py python program print('the meaning of life'running shell commands none of this is directly related to pythonof course (despite the fact that python command-line scripts are sometimes confusingly called "shell tools"but because the os module' system and popen calls let python scripts run any sort of command that the underlying system shell understandsour scripts can make use of every command-line tool available on the computerwhether it' coded in python or not for examplehere introducing the os module
4,672
shown previouslyc:\pp \systempython import os os system('dir / 'helloshell py more py more pyc spam txt __init__ py os system('type helloshell py' python program print('the meaning of life' os system('type hellshell py'the system cannot find the file specified the at the end of the first two commands here are just the return values of the system call itself (its exit statuszero generally means successthe system call can be used to run any command line that we could type at the shell' prompt (herec:\pp \system>the command' output normally shows up in the python session' or program' standard output stream communicating with shell commands but what if we want to grab command' output within scriptthe os system call simply runs shell command linebut os popen also connects to the standard input or output streams of the commandwe get back file-like object connected to the command' output by default (if we pass mode flag to popenwe connect to the command' input stream insteadby using this object to read the output of command spawned with popenwe can intercept the text that would normally appear in the console window where command line is typedopen('helloshell py'read(" python program\nprint('the meaning of life')\ntext os popen('type helloshell py'read(text " python program\nprint('the meaning of life')\nlisting os popen('dir / 'readlines(listing ['helloshell py\ ''more py\ ''more pyc\ ''spam txt\ ''__init__ py\ 'herewe first fetch file' content the usual way (using python files)then as the output of shell type command reading the output of dir command lets us get listing of files in directory that we can then process in loop we'll learn other ways to obtain such list in there we'll also learn how file iterators make the readlines call system tools
4,673
list interactively as we did here (see also "subprocessos popenand iteratorson page for more on the subjectso farwe've run basic dos commandsbecause these calls can run any command line that we can type at shell promptthey can also be used to launch other python scripts assuming your system search path is set to locate your python (so that you can use the shorter "pythonin the following instead of the longer " :\python \python")os system('python helloshell py'run python program the meaning of life output os popen('python helloshell py'read(output 'the meaning of life\nin all of these examplesthe command-line strings sent to system and popen are hardcodedbut there' no reason python programs could not construct such strings at runtime using normal string operations (+%etc given that commands can be dynamically built and run this waysystem and popen turn python scripts into flexible and portable tools for launching and orchestrating other programs for examplea python test "driverscript can be used to run programs coded in any language ( ++javapythonand analyze their output we'll explore such script in we'll also revisit os popen in the next in conjunction with stream redirectionas we'll findthis call can also send input to programs the subprocess module alternative as mentionedin recent releases of python the subprocess module can achieve the same effect as os system and os popenit generally requires extra code but gives more control over how streams are connected and used this becomes especially useful when streams are tied in more complex ways for exampleto run simple shell command like we did with os system earlierthis new module' call function works roughly the same (running commands like "typethat are built into the shell on windows requires extra protocolthough normal executables like "pythondo not)import subprocess subprocess call('python helloshell py'the meaning of life subprocess call('cmd / "type helloshell py"' python program print('the meaning of life' subprocess call('type helloshell py'shell=truea python program print('the meaning of life' roughly like os system(built-in shell cmd alternative for built-ins introducing the os module
4,674
on windowswe need to pass shell=true argument to subprocess tools like call and popen (shown aheadin order to run commands built into the shell windows commands like "typerequire this extra protocolbut normal executables like "pythondo not on unix-like platformswhen shell is false (its default)the program command line is run directly by os execvpa call we'll meet in if this argument is truethe command-line string is run through shell insteadand you can specify the shell to use with additional arguments more on some of this laterfor nowit' enough to note that you may need to pass shell=true to run some of the examples in this section and book in unix-like environmentsif they rely on shell features like program path lookup since ' running code on windowsthis argument will often be omitted here besides imitating os systemwe can similarly use this module to emulate the os popen call used earlierto run shell command and obtain its standard output text in our scriptpipe subprocess popen('python helloshell py'stdout=subprocess pipepipe communicate(( 'the meaning of life\ \ 'nonepipe returncode herewe connect the stdout stream to pipeand communicate to run the command to completion and receive its standard output and error streamstextthe command' exit status is available in an attribute after it completes alternativelywe can use other interfaces to read the command' standard output directly and wait for it to exit (which returns the exit status)pipe subprocess popen('python helloshell py'stdout=subprocess pipepipe stdout read( 'the meaning of life\ \npipe wait( in factthere are direct mappings from os popen calls to subprocess popen objectsfrom subprocess import popenpipe popen('python helloshell py'stdout=pipecommunicate()[ 'the meaning of life\ \nimport os os popen('python helloshell py'read('the meaning of life\nas you can probably tellsubprocess is extra work in these relatively simple cases it starts to look betterthoughwhen we need to control additional streams in flexible ways in factbecause it also allows us to process command' error and input streams system tools
4,675
and os popen calls which were available in python xthese are now just use cases for subprocess object interfaces because more advanced use cases for this module deal with standard streamswe'll postpone additional details about this module until we study stream redirection in the next shell command limitations before we move onyou should keep in mind two limitations of system and popen firstalthough these two functions themselves are fairly portabletheir use is really only as portable as the commands that they run the preceding examples that run dos dir and type shell commandsfor instancework only on windowsand would have to be changed in order to run ls and cat commands on unix-like platforms secondit is important to remember that running python files as programs this way is very different and generally much slower than importing program files and calling functions they define when os system and os popen are calledthey must start brandnewindependent program running on your operating system (they generally run the command in new processwhen importing program file as modulethe python interpreter simply loads and runs the file' code in the same process in order to generate module object no other program is spawned along the way ss there are good reasons to build systems as separate programstooand in the next we'll explore things such as command-line arguments and streams that allow programs to pass information back and forth but in many casesimported modules are faster and more direct way to compose systems if you plan to use these calls in earnestyou should also know that the os system call normally blocks--that ispauses--its caller until the spawned command line exits on linux and unix-like platformsthe spawned command can generally be made to run independently and in parallel with the caller by adding an shell background operator at the end of the command lineos system("python program py arg arg &"on windowsspawning with dos start command will usually launch the command in parallel tooos system("start program py arg arg"ss the python code exec(open(fileread()also runs program file' codebut within the same process that called it it' similar to an import in that regardbut it works more as if the file' text had been pasted into the calling program at the place where the exec call appears (unless explicit global or local namespace dictionaries are passedunlike importssuch an exec unconditionally reads and executes file' code (it may be run more than once per process)no module object is generated by the file' executionand unless optional namespace dictionaries are passed inassignments in the file' code may overwrite variables in the scope where the exec appearssee other resources or the python library manual for more details introducing the os module
4,676
this call opens file with whatever program is listed in the windows registry for the file' type--as though its icon has been clicked with the mouse cursoros startfile("webpage html"os startfile("document doc"os startfile("myscript py"open file in your web browser open file in microsoft word run file with python the os popen call does not generally block its caller (by definitionthe caller must be able to read or write the file object returnedbut callers may still occasionally become blocked under both windows and linux if the pipe object is closed-- when garbage is collected--before the spawned program exits or the pipe is read exhaustively ( with its read(methodas we will see later in this part of the bookthe unix os fork/exec and windows os spawnv calls can also be used to run parallel programs without blocking because the os module' system and popen callsas well as the subprocess modulealso fall under the category of program launchersstream redirectorsand cross-process communication devicesthey will show up again in the following so we'll defer further details for the time being if you're looking for more details right awaybe sure to see the stream redirection section in the next and the directory listings section in other os module exports that' as much of tour around os as we have space for here since most other os module tools are even more difficult to appreciate outside the context of larger application topicswe'll postpone deeper look at them until later but to let you sample the flavor of this modulehere is quick preview for reference among the os module' other weapons are theseos environ fetches and sets shell environment variables os fork spawns new child process on unix-like systems os pipe communicates between programs os execlp starts new programs os spawnv starts new programs with lower-level control os open opens low-level descriptor-based file os mkdir creates new directory system tools
4,677
creates new named pipe os stat fetches low-level file information os remove deletes file by its pathname os walk applies function or loop body to all parts of an entire directory tree and so on one caution up frontthe os module provides set of file openreadand write callsbut all of these deal with low-level file access and are entirely distinct from python' built-in stdio file objects that we create with the built-in open function you should normally use the built-in open functionnot the os modulefor all but very special file-processing needs ( opening with exclusive access file lockingin the next we will apply sys and os tools such as those we've introduced here to implement common system-level tasksbut this book doesn' have space to provide an exhaustive list of the contents of modules we will meet along the way againif you have not already done soyou should become acquainted with the contents of modules such as os and sys using the resources described earlier for nowlet' move on to explore additional system tools in the context of broader system programming concepts--the context surrounding running script subprocessos popenand iterators in we'll explore file iteratorsbut you've probably already studied the basics prior to picking up this book because os popen objects have an iterator that reads one line at timetheir readlines method call is usually superfluous for examplethe following steps through lines produced by another program without any explicit readsimport os for line in os popen('dir / py')print(lineend=''helloshell py more py __init__ py interestinglypython implements os popen using the subprocess popen object that we studied in this you can see this for yourself in file os py in the python standard library on your machine (see :\python \lib on windows)the os popen result is an object that manages the popen object and its piped streami os popen('dir / py' because this pipe wrapper object defines an __iter__ methodit supports line iterationboth automatic ( the for loop aboveand manual curiouslyalthough the pipe wrapper object supports direct __next__ method calls as though it were its own iterator introducing the os module
4,678
latter is supposed to simply call the formeri os popen('dir / py' __next__('helloshell py\ni os popen('dir / py'next(itypeerror_wrap_close object is not an iterator the reason for this is subtle--direct __next__ calls are intercepted by __getattr__ defined in the pipe wrapper objectand are properly delegated to the wrapped objectbut next function calls invoke python' operator overloading machinerywhich in bypasses the wrapper' __getattr__ for special method names like __next__ since the pipe wrapper object doesn' define __next__ of its ownthe call is not caught and delegatedand the next built-in fails as explained in full in the book learning pythonthe wrapper' __getattr__ isn' tried because begins such searches at the classnot the instance this behavior may or may not have been anticipatedand you don' need to care if you iterate over pipe lines automatically with for loopscomprehensionsand other tools to code manual iterations robustlythoughbe sure to call the iter built-in first--this invokes the __iter__ defined in the pipe wrapper object itselfto correctly support both flavors of advancementi os popen('dir / py' iter(ii __next__('helloshell py\nnext( 'more py\ system tools what for loops do now both forms work
4,679
script execution context " ' like to have an argumentpleasepython scripts don' run in vacuum (despite what you may have hearddepending on platforms and startup procedurespython programs may have all sorts of enclosing context--information automatically passed in to the program by the operating system when the program starts up for instancescripts have access to the following sorts of system-level inputs and interfacescurrent working directory os getcwd gives access to the directory from which script is startedand many file tools use its value implicitly command-line arguments sys argv gives access to words typed on the command line that are used to start the program and that serve as script inputs shell variables os environ provides an interface to names assigned in the enclosing shell (or parent programand passed in to the script standard streams sys stdinstdoutand stderr export the three input/output streams that are at the heart of command-line shell toolsand can be leveraged by scripts with print optionsthe os popen call and subprocess module introduced in the io stringio classand more such tools can serve as inputs to scriptsconfiguration parametersand so on in this we will explore all these four context' tools--both their python interfaces and their typical roles
4,680
the notion of the current working directory (cwdturns out to be key concept in some scriptsexecutionit' always the implicit place where files processed by the script are assumed to reside unless their names have absolute directory paths as we saw earlieros getcwd lets script fetch the cwd name explicitlyand os chdir allows script to move to new cwd keep in mindthoughthat filenames without full pathnames map to the cwd and have nothing to do with your pythonpath setting technicallya script is always launched from the cwdnot the directory containing the script file converselyimports always first search the directory containing the scriptnot the cwd (unless the script happens to also be located in the cwdsince this distinction is subtle and tends to trip up beginnerslet' explore it in bit more detail cwdfilesand import paths when you run python script by typing shell command line such as python dir \dir \file pythe cwd is the directory you were in when you typed this commandnot dir \dir on the other handpython automatically adds the identity of the script' home directory to the front of the module search path such that file py can always import other files in dir \dir no matter where it is run from to illustratelet' write simple script to echo both its cwd and its module search pathc:\pp \systemtype whereami py import ossys print('my os getcwd =>'os getcwd()print('my sys path =>'sys path[: ]input(show my cwd execution dir show first import paths wait for keypress if clicked nowrunning this script in the directory in which it resides sets the cwd as expected and adds it to the front of the module import search path we met the sys path module search path earlierits first entry might also be the empty string to designate cwd when you're working interactivelyand most of the cwd has been truncated to here for displayc:\pp \systemset pythonpath= :\pp thed\examples :\pp \systempython whereami py my os getcwd = :\pp \system my sys path =[' :\\\pp \\system'' :\\pp thed\\examples'more but if we run this script from other placesthe cwd moves with us (it' the directory where we type commands)and python adds directory to the front of the module search path that allows the script to still see files in its own home directory for instancewhen running from one level up )the system name added to the front of sys path will be the first directory that python searches for imports within whereami pyit points imports back to the directory containing the script that was run filenames without script execution context
4,681
not the system subdirectory nested therec:\pp \systemcd :\pp epython system\whereami py my os getcwd = :\pp my sys path =[' :\\\pp \\system'' :\\pp thed\\examples'more :\pp ecd system\temp :\pp \system\temppython \whereami py my os getcwd = :\pp \system\temp my sys path =[' :\\\pp \\system'' :\\pp thed\\examples'the net effect is that filenames without directory paths in script will be mapped to the place where the command was typed (os getcwd)but imports still have access to the directory of the script being run (via the front of sys pathfinallywhen file is launched by clicking its iconthe cwd is just the directory that contains the clicked file the following outputfor exampleappears in new dos console box when whereami py is double-clicked in windows explorermy os getcwd = :\pp \system my sys path =[' :\\\pp \\system'more in this caseboth the cwd used for filenames and the first import search directory are the directory containing the script file this all usually works out just as you expectbut there are two pitfalls to avoidfilenames might need to include complete directory paths if scripts cannot be sure from where they will be run command-line scripts cannot always rely on the cwd to gain import visibility to files that are not in their own directoriesinsteaduse pythonpath settings and package import paths to access modules in other directories for examplescripts in this bookregardless of how they are runcan always import other files in their own home directories without package path imports (import file here)but must go through the pp package root to find files anywhere else in the examples tree (from pp dir dir import filethere)even if they are run from the directory containing the desired external module as usual for modulesthe pp \dir \dir directory name could also be added to pythonpath to make files there visible everywhere without package path imports (though adding more directories to python path increases the likelihood of name clashesin either casethoughimports are always resolved to the script' home directory or other python search path settingsnot to the cwd current working directory
4,682
this distinction between the cwd and import search paths explains why many scripts in this book designed to operate in the current working directory (instead of one whose name is passed inare run with command lines such as this onec:\temppython :\pp \tools\cleanpyc py process cwd in this examplethe python script file itself lives in the directory :\pp \toolsbut because it is run from :\tempit processes the files located in :\temp ( in the cwdnot in the script' home directoryto process files elsewhere with such scriptsimply cd to the directory to be processed to change the cwdc:\tempcd :\pp thed\examples :\pp thed\examplespython :\pp \tools\cleanpyc py process cwd because the cwd is always implieda cd command tells the script which directory to process in no less certain terms than passing directory name to the script explicitlylike this (portability noteyou may need to add quotes around the py in this and other command-line examples to prevent it from being expanded in some unix shells) :\pp \toolspython find py py :\temp process named dir in this command linethe cwd is the directory containing the script to be run (notice that the script filename has no directory path prefix)but since this script processes directory named explicitly on the command line ( :\temp)the cwd is irrelevant finallyif we want to run such script located in some other directory in order to process files located in yet another directorywe can simply give directory paths to bothc:\temppython :\pp \tools\find py cxx :\pp thed\examples\pp herethe script has import visibility to files in its pp \tools home directory and processes files in the directory named on the command linebut the cwd is something else entirely ( :\tempthis last form is more to typeof coursebut watch for variety of cwd and explicit script-path command lines like these in this book command-line arguments the sys module is also where python makes available the words typed on the command that is used to start python script these words are usually referred to as commandline arguments and show up in sys argva built-in list of strings programmers may notice its similarity to the argv array (an array of stringsit' not much to look at interactivelybecause no command-line arguments are passed to start up python in this modeimport sys sys argv ['' script execution context
4,683
line example - shows an unreasonably simple one that just prints the argv list for inspection example - pp \system\testargv py import sys print(sys argvrunning this script prints the command-line arguments listnote that the first item is always the name of the executed python script file itselfno matter how the script was started (see "executable scripts on unixon page :\pp \systempython testargv py ['testargv py' :\pp \systempython testargv py spam eggs cheese ['testargv py''spam''eggs''cheese' :\pp \systempython testargv py - data txt - results txt ['testargv py''- ''data txt''- ''results txt'the last command here illustrates common convention much like function argumentscommand-line options are sometimes passed by position and sometimes by name using "-name valueword pair for instancethe pair - data txt means the - option' value is data txt ( an input filenameany words can be listedbut programs usually impose some sort of structure on them command-line arguments play the same role in programs that function arguments do in functionsthey are simply way to pass information to program that can vary per program run because they don' have to be hardcodedthey allow scripts to be more generally useful for examplea file-processing script can use command-line argument as the name of the file it should processsee ' more py script (example - for prime example other scripts might accept processing mode flagsinternet addressesand so on parsing command-line arguments once you start using command-line arguments regularlythoughyou'll probably find it inconvenient to keep writing code that fishes through the list looking for words more typicallyprograms translate the arguments list on startup into structures that are more conveniently processed here' one way to do itthe script in example - scans the argv list looking for -optionname optionvalue word pairs and stuffs them into dictionary by option name for easy retrieval command-line arguments
4,684
"collect command-line options in dictionarydef getopts(argv)opts {while argvif argv[ ][ ='-'opts[argv[ ]argv[ argv argv[ :elseargv argv[ :return opts if __name__ ='__main__'from sys import argv myargs getopts(argvif '-iin myargsprint(myargs['- ']print(myargsfind "-name valuepairs dict key is "-namearg example client code you might import and use such function in all your command-line tools when run by itselfthis file just prints the formatted argument dictionaryc:\pp \systempython testargv py { :\pp \systempython testargv py - data txt - results txt data txt {'- ''results txt''- ''data txt'naturallywe could get much more sophisticated here in terms of argument patternserror checkingand the like for more complex command lineswe could also use command-line processing tools in the python standard library to parse argumentsthe getopt modulemodeled after unix/ utility of the same name the optparse modulea newer alternativegenerally considered to be more powerful both of these are documented in python' library manualwhich also provides usage examples which we'll defer to here in the interest of space in generalthe more configurable your scriptsthe more you must invest in command-line processing logic complexity executable scripts on unix unix and linux usersyou can also make text files of python source code directly executable by adding special line at the top with the path to the python interpreter and giving the file executable permission for instancetype this code into text file called myscript#!/usr/bin/python print('and nice red uniforms' script execution context
4,685
this file is runthe operating system sends lines in this file to the interpreter listed after #in line if this file is made directly executable with shell command of the form chmod + myscriptit can be run directly without typing python in the commandas though it were binary executable programmyscript and nice red uniforms when run this waysys argv will still have the script' name as the first word in the list["myscript"" "" "" "]exactly as if the script had been run with the more explicit and portable command form python myscript making scripts directly executable is actually unix tricknot python featurebut it' worth pointing out that it can be made bit less machine dependent by listing the unix env command at the top instead of hardcoded path to the python executable#!/usr/bin/env python print('wait for it 'when coded this waythe operating system will employ your environment variable settings to locate your python interpreter (your path variableon most platformsif you run the same script on many machinesyou need only change your environment settings on each machine (you don' need to edit python script codeof courseyou can always run python files with more explicit command linepython myscript this assumes that the python interpreter program is on your system' search path setting (otherwiseyou need to type its full path)but it works on any python platform with command line since this is more portablei generally use this convention in the book' examplesbut consult your unix manpages for more details on any of the topics mentioned here even sothese special #lines will show up in many examples in this book just in case readers want to run them as executables on unix or linuxon other platformsthey are simply ignored as python comments note that on recent flavors of windowsyou can usually also type script' filename directly (without the word pythonto make it goand you don' have to add #line at the top python uses the windows registry on this platform to declare itself as the program that opens files with python extensions py and othersthis is also why you can launch files on windows by clicking on them shell environment variables shell variablessometimes known as environment variablesare made available to python scripts as os environa python dictionary-like object with one entry per variable setting in the shell shell variables live outside the python systemthey are often set at your system prompt or within startup files or control-panel guis and typically serve as system-wide configuration inputs to programs shell environment variables
4,686
search path setting is shell variable used by python to import modules by setting it once in your operating systemits value is available every time python program is run shell variables can also be set by programs to serve as inputs to other programs in an applicationbecause their values are normally inherited by spawned programsthey can be used as simple form of interprocess communication fetching shell variables in pythonthe surrounding shell environment becomes simple preset objectnot special syntax indexing os environ by the desired shell variable' name string ( os environ['user']is the moral equivalent of adding dollar sign before variable name in most unix shells ( $user)using surrounding percent signs on dos (%user%)and calling getenv("user"in program let' start up an interactive session to experiment (run in python on windows laptop)import os os environ keys(keysview(list(os environ keys()['tmp''computername''userdomain''psmodulepath''commonprogramfiles'many more deleted 'number_of_processors''processor_level''userprofile''os''public''qtjava'os environ['temp'' :\\users\\mark\\appdata\\local\\tempherethe keys method returns an iterable of assigned variablesand indexing fetches the value of the shell variable temp on windows this works the same way on linuxbut other variables are generally preset when python starts up since we know about pythonpathlet' peek at its setting within python to verify its content (as wrote thismine was set to the root of the book examples tree for this fourth editionas well as temporary development location)os environ['pythonpath'' :\\pp thed\\examples; :\\users\\mark\\tempfor srcdir in os environ['pythonpath'split(os pathsep)print(srcdirc:\pp thed\examples :\users\mark\temp import sys sys path[: [''' :\\pp thed\\examples'' :\\users\\mark\\temp'pythonpath is string of directory paths separated by whatever character is used to separate items in such paths on your platform ( on dos/windowson unix and linuxto split it into its componentswe pass to the split string method an script execution context
4,687
result of merging in the pythonpath setting after the current directory changing shell variables like normal dictionariesthe os environ object supports both key indexing and assignment as for dictionariesassignments change the value of the keyos environ['temp'' :\\users\\mark\\appdata\\local\\temp os environ['temp' ' :\tempos environ['temp'' :\\tempbut something extra happens here in all recent python releasesvalues assigned to os environ keys in this fashion are automatically exported to other parts of the application that iskey assignments change both the os environ object in the python program as well as the associated variable in the enclosing shell environment of the running program' process its new value becomes visible to the python programall linked-in modulesand any programs spawned by the python process internallykey assignments to os environ call os putenv-- function that changes the shell variable outside the boundaries of the python interpreter to demonstrate how this workswe need couple of scripts that set and fetch shell variablesthe first is shown in example - example - pp \system\environment\setenv py import os print('setenv 'end='print(os environ['user']show current shell variable value os environ['user''brianos system('python echoenv py'runs os putenv behind the scenes os environ['user''arthuros system('python echoenv py'changes passed to spawned programs and linked-in library modules os environ['user'input('?'print(os popen('python echoenv py'read()this setenv py script simply changes shell variableuserand spawns another script that echoes this variable' valueas shown in example - example - pp \system\environment\echoenv py import os print('echoenv 'end='print('hello,'os environ['user']shell environment variables
4,688
when run from the command linethis value comes from whatever we've set the variable to in the shell itselfc:\pp \system\environmentset user=bob :\pp \system\environmentpython echoenv py echoenv hellobob when spawned by another script such as setenv py using the os system and os popen tools we met earlierthoughechoenv py gets whatever user settings its parent program has madec:\pp \system\environmentpython setenv py setenv bob echoenv hellobrian echoenv helloarthur ?gumby echoenv hellogumby :\pp \system\environmentecho %userbob this works the same way on linux in general termsa spawned program always inherits environment settings from its parents spawned programs are programs started with python tools such as os spawnvthe os fork/exec combination on unix-like platformsand os popenos systemand the subprocess module on variety of platforms all programs thus launched get the environment variable settings that exist in the parent at launch time from larger perspectivesetting shell variables like this before starting new program is one way to pass information into the new program for instancea python configuration script might tailor the pythonpath variable to include custom directories just before launching another python scriptthe launched script will have the custom search path in its sys path because shell variables are passed down to children (in factwatch for such launcher script to appear at the end of shell variable fine pointsparentsputenvand getenv notice the last command in the preceding example--the user variable is back to its original value after the top-level python program exits assignments to os environ keys are passed outside the interpreter and down the spawned programs chainbut never back up to parent program processes (including the system shellthis is also true in programs that use the putenv library calland it isn' python limitation per se this is by default some program-launching tools also let scripts pass environment settings that are different from their own to child programs for instancethe os spawnve call is like os spawnvbut it accepts dictionary argument representing the shell environment to be passed to the started program some os execvariants (ones with an "eat the end of their namessimilarly accept explicit environmentssee the os execcall formats in for more details script execution context
4,689
keep in mind that shell settings made within program usually endure only for that program' run and for the run of its spawned children if you need to export shell variable setting so that it lives on after python exitsyou may be able to find platformspecific extensions that do thissearch another subtletyas implemented todaychanges to os environ automatically call os putenvwhich runs the putenv call in the library if it is available on your platform to export the setting outside python to any linked-in code howeveralthough os environ changes call os putenvdirect calls to os putenv do not update os environ to reflect the change because of thisthe os environ mapping interface is generally preferred to os putenv also note that environment settings are loaded into os environ on startup and not on each fetchhencechanges made by linked-in code after startup may not be reflected in os environ python does have more focused os getenv call todaybut it is simply translated into an os environ fetch on most platforms (or allin )not into call to getenv in the library most applications won' need to careespecially if they are pure python code on platforms without putenv callos environ can be passed as parameter to program startup tools to set the spawned program' environment standard streams the sys module is also the place where the standard inputoutputand error streams of your python programs livethese turn out to be another common way for programs to communicateimport sys for in (sys stdinsys stdoutsys stderr)print(fencoding='cp 'encoding='cp 'encoding='cp 'the standard streams are simply preopened python file objects that are automatically connected to your program' standard streams when python starts up by defaultall of them are tied to the console window where python (or python programwas started because the print and input built-in functions are really nothing more than userfriendly interfaces to the standard output and input streamsthey are similar to using stdout and stdin in sys directlyprint('hello stdout world'hello stdout world sys stdout write('hello stdout world'\ 'hello stdout world standard streams
4,690
hello stdin world>spam 'spamprint('hello stdin world>')sys stdin readline()[:- hello stdin worldeggs 'eggsstandard streams on windows windows usersif you click py python program' filename in windows file explorer to start it (or launch it with os system) dos console window automatically pops up to serve as the program' standard stream if your program makes windows of its ownyou can avoid this console pop-up window by naming your program' source-code file with pyw extensionnot with py extension the pyw extension simply means py source file without dos pop up on windows (it uses windows registry settings to run custom version of pythona pyw file may also be imported as usual also note that because printed output goes to this dos pop up when program is clickedscripts that simply print text and exit will generate an odd "flash"--the dos console box pops upoutput is printed into itand the pop up goes away immediately (not the most user-friendly of features!to keep the dos pop-up box around so that you can read printed outputsimply add an input(call at the bottom of your script to pause for an enter key press before exiting redirecting streams to files and programs technicallystandard output (and printtext appears in the console window where program was startedstandard input (and inputtext comes from the keyboardand standard error text is used to print python error messages to the console window at least that' the default it' also possible to redirect these streams both to files and to other programs at the system shellas well as to arbitrary objects within python script on most systemssuch redirections make it easy to reuse and combine general-purpose command-line utilities redirection is useful for things like canned (precodedtest inputswe can apply single test script to any set of inputs by simply redirecting the standard input stream to different file each time the script is run similarlyredirecting the standard output stream lets us save and later analyze program' outputfor exampletesting systems might compare the saved standard output of script with file of expected output to detect failures although it' powerful paradigmredirection turns out to be straightforward to use for instanceconsider the simple read-evaluate-print loop program in example - script execution context
4,691
"read numbers till eof and show squaresdef interact()print('hello stream world'print sends to sys stdout while truetryreply input('enter number>'input reads sys stdin except eoferrorbreak raises an except on eof elseinput given as string num int(replyprint("% squared is % (numnum * )print('bye'if __name__ ='__main__'interact(when runnot imported as usualthe interact function here is automatically executed when this file is runnot when it is imported by defaultrunning this file from system command line makes that standard stream appear where you typed the python command the script simply reads numbers until it reaches end-of-file in the standard input stream (on windowsend-of-file is usually the two-key combination ctrl-zon unixtype ctrl- instead+) :\pp \system\streamspython teststreams py hello stream world enter number> squared is enter number> squared is enter number>^ bye but on both windows and unix-like platformswe can redirect the standard input stream to come from file with the filename shell syntax here is command session in dos console box on windows that forces the script to read its input from text fileinput txt it' the same on linuxbut replace the dos type command with unix cat commandc:\pp \system\streamstype input txt :\pp \system\streamspython teststreams py input txt hello stream world notice that input raises an exception to signal end-of-filebut file read methods simply return an empty string for this condition because input also strips the end-of-line character at the end of linesan empty string result means an empty lineso an exception is necessary to specify the end-of-file condition file read methods retain the end-of-line character and denote an empty line as "\ninstead of "this is one way in which reading sys stdin directly differs from input the latter also accepts prompt string that is automatically printed before input is accepted standard streams
4,692
enter number> squared is enter number>bye herethe input txt file automates the input we would normally type interactively--the script reads from this file rather than from the keyboard standard output can be similarly redirected to go to file with the filename shell syntax in factwe can combine input and output redirection in single commandc:\pp \system\streamspython teststreams py output txt :\pp \system\streamstype output txt hello stream world enter number> squared is enter number> squared is enter number>bye this timethe python script' input and output are both mapped to text filesnot to the interactive console session chaining programs with pipes on windows and unix-like platformsit' also possible to send the standard output of one program to the standard input of another using the shell character between two commands this is usually called "pipeoperation because the shell creates pipeline that connects the output and input of two commands let' send the output of the python script to the standard more command-line program' input to see how this worksc:\pp \system\streamspython teststreams py input txt more hello stream world enter number> squared is enter number> squared is enter number>bye hereteststreams' standard input comes from file againbut its output (written by print callsis sent to another programnot to file or window the receiving program is morea standard command-line paging program available on windows and unix-like platforms because python ties scripts into the standard stream modelthoughpython scripts can be used on both ends one python script' output can always be piped into another python script' inputc:\pp \system\streamstype writer py print("helphelpi' being repressed!"print( :\pp \system\streamstype reader py print('got this"% "input()import sys data sys stdin readline()[:- print('the meaning of life is'dataint(data script execution context
4,693
helphelpi' being repressed :\pp \system\streamspython writer py python reader py got this"helphelpi' being repressed!the meaning of life is this timetwo python programs are connected script reader gets input from script writerboth scripts simply read and writeoblivious to stream mechanics in practicesuch chaining of programs is simple form of cross-program communications it makes it easy to reuse utilities written to communicate via stdin and stdout in ways we never anticipated for instancea python program that sorts stdin text could be applied to any data source we likeincluding the output of other scripts consider the python command-line utility scripts in examples - and - which sort and sum lines in the standard input stream example - pp \system\streams\sorter py import sys lines sys stdin readlines(lines sort(for line in linesprint(lineend=''or sorted(sys stdinsort stdin input linessend result to stdout for further processing example - pp \system\streams\adder py import sys sum while truetryline input(except eoferrorbreak elsesum +int(lineprint(sumor call sys stdin readlines(or for line in sys stdininput strips \ at end was sting atoi(in nd ed we can apply such general-purpose tools in variety of ways at the shell command line to sort and sum arbitrary files and program outputs (windows noteon my prior xp machine and python xi had to type "python file pyherenot just "file py,or else the input redirection failedwith python on windows todayeither form works) :\pp \system\streamstype data txt :\pp \system\streamspython sorter py data txt sort file standard streams
4,694
sum file :\pp \system\streamstype data txt python adder py sum type output :\pp \system\streamstype writer py for data in ( )print('% ddatac:\pp \system\streamspython writer py python sorter py sort py output :\pp \system\streamswriter py sorter py same output as prior command on windows shorter form :\pp \system\streamspython writer py python sorter py python adder py the last command here connects three python scripts by standard streams--the output of each prior script is fed to the input of the next via pipeline shell syntax coding alternatives for adders and sorters few coding pointers hereif you look closelyyou'll notice that sorter py reads all of stdin at once with the readlines methodbut adder py reads one line at time if the input source is another programsome platforms run programs connected by pipes in parallel on such systemsreading line by line works better if the data streams being passed are largebecause readers don' have to wait until writers are completely finished to get busy processing data because input just reads stdinthe line-by-line scheme used by adder py can always be coded with manual sys stdin reads tooc:\pp \system\streamstype adder py import sys sum while trueline sys stdin readline(if not linebreak sum +int(lineprint(sumthis version utilizes the fact that int allows the digits to be surrounded by whitespace (readline returns line including its \nbut we don' have to use [:- or rstrip(to remove it for intin factwe can use python' more recent file iterators to achieve the same effect--the for loopfor exampleautomatically grabs one line each time through when we iterate over file object directly (more on file iterators in the next :\pp \system\streamstype adder py import sys sum script execution context
4,695
print(sumchanging sorter to read line by line this way may not be big performance boostthoughbecause the list sort method requires that the list already be complete as we'll see in manually coded sort algorithms are generally prone to be much slower than the python list sorting method interestinglythese two scripts can also be coded in much more compact fashion in python and later by using the new sorted built-in functiongenerator expressionsand file iterators the following work the same way as the originalswith noticeably less source-file real estatec:\pp \system\streamstype sortersmall py import sys for line in sorted(sys stdin)print(lineend='' :\pp \system\streamstype addersmall py import sys print(sum(int(linefor line in sys stdin)in its argument to sumthe latter of these employs generator expressionwhich is much like list comprehensionbut results are returned one at timenot in physical list the net effect is space optimization for more detailssee core language resourcesuch as the book learning python redirected streams and user interaction earlier in this sectionwe piped teststreams py output into the standard more commandline program with command like thisc:\pp \system\streamspython teststreams py input txt more but since we already wrote our own "morepaging utility in python in the preceding why not set it up to accept input from stdin toofor exampleif we change the last three lines of the more py file listed as example - in the prior if __name__ ='__main__'import sys if len(sys argv= more(sys stdin read()elsemore(open(sys argv[ ]read()when runnot when imported page stdin if no cmd args it almost seems as if we should be able to redirect the standard output of teststreams py into the standard input of more pyc:\pp \system\streamspython teststreams py input txt python \more py hello stream world enter number> squared is enter number> squared is enter number>bye standard streams
4,696
from file again andas in the last sectionone python program' output is piped to another' input--the more py script in the parent directory but there' subtle problem lurking in the preceding more py command reallychaining worked there only by sheer luckif the first script' output is long enough that more has to ask the user if it should continuethe script will utterly fail (specificallywhen input for user interaction triggers eoferrorthe problem is that the augmented more py uses stdin for two disjointed purposes it reads reply from an interactive user on stdin by calling inputbut now it also accepts the main input text on stdin when the stdin stream is really redirected to an input file or pipewe can' use it to input reply from an interactive userit contains only the text of the input source moreoverbecause stdin is redirected before the program even starts upthere is no way to know what it meant prior to being redirected in the command line if we intend to accept input on stdin and use the console for user interactionwe have to do bit morewe would also need to use special interfaces to read user replies from keyboard directlyinstead of standard input on windowspython' standard library msvcrt module provides such toolson many unix-like platformsreading from device file /dev/tty will usually suffice since this is an arguably obscure use casewe'll delegate complete solution to suggested exercise example - shows windows-only modified version of the more script that pages the standard input stream if called with no argumentsbut also makes use of lower-level and platform-specific tools to converse with user at keyboard if needed example - pp \system\streams\moreplus py ""split and interactively page stringfileor stream of text to stdoutwhen run as scriptpage stdin or file whose name is passed on cmdlineif input is stdincan' use it for user reply--use platform-specific tools or gui""import sys def getreply()""read reply key from an interactive user even if stdin redirected to file or pipe ""if sys stdin isatty()return input('?'elseif sys platform[: ='win'import msvcrt msvcrt putch( '?' script execution context if stdin is console read reply line from stdin if stdin was redirected can' use to ask user
4,697
use windows console tools msvcrt putch( '\ 'getch(does not echo key return key elseassert false'platform not supported#linux?open('/dev/tty'readline()[:- def more(textnumlines= )""page multiline string to stdout ""lines text splitlines(while lineschunk lines[:numlineslines lines[numlines:for line in chunkprint(lineif lines and getreply(not in [ ' ' ' ']break if __name__ ='__main__'if len(sys argv= more(sys stdin read()elsemore(open(sys argv[ ]read()when runnot when imported if no command-line arguments page stdinno inputs else page filename argument most of the new code in this version shows up in its getreply function the file' isatty method tells us whether stdin is connected to the consoleif it iswe simply read replies on stdin as before of coursewe have to add such extra logic only to scripts that intend to interact with console users and take input on stdin in gui applicationfor examplewe could instead pop up dialogsbind keyboard-press events to run callbacksand so on (we'll meet guis in armed with the reusable getreply functionthoughwe can safely run our moreplus utility in variety of ways as beforewe can import and call this module' function directlypassing in whatever string we wish to pagefrom moreplus import more more(open('addersmall py'read()import sys print(sum(int(linefor line in sys stdin)also as beforewhen run with command-line argumentthis script interactively pages through the named file' textc:\pp \system\streamspython moreplus py addersmall py import sys print(sum(int(linefor line in sys stdin) :\pp \system\streamspython moreplus py moreplus py ""split and interactively page stringfileor stream of text to stdoutwhen run as scriptpage stdin or file whose name is passed on cmdlineif input is stdincan' use it for user reply--use platform-specific tools or gui""standard streams
4,698
def getreply()? but now the script also correctly pages text redirected into stdin from either file or command pipeeven if that text is too long to fit in single display chunk on most shellswe send such input via redirection or pipe operators like thesec:\pp \system\streamspython moreplus py moreplus py ""split and interactively page stringfileor stream of text to stdoutwhen run as scriptpage stdin or file whose name is passed on cmdlineif input is stdincan' use it for user reply--use platform-specific tools or gui""import sys def getreply()? :\pp \system\streamstype moreplus py python moreplus py ""split and interactively page stringfileor stream of text to stdoutwhen run as scriptpage stdin or file whose name is passed on cmdlineif input is stdincan' use it for user reply--use platform-specific tools or gui""import sys def getreply()? finallypiping one python script' output into this script' input now works as expectedwithout botching user interaction (and not just because we got lucky)\system\streamspython teststreams py input txt python moreplus py hello stream world enter number> squared is enter number> squared is enter number>bye herethe standard output of one python script is fed to the standard input of another python script located in the same directorymoreplus py reads the output of teststreams py all of the redirections in such command lines work only because scripts don' care what standard input and output really are--interactive usersfilesor pipes between programs for examplewhen run as scriptmoreplus py simply reads stream sys stdinthe command-line shell ( dos on windowscsh on linuxattaches such streams to the source implied by the command line before the script is started script execution context
4,699
and for readers keeping countwe have just run this single more pager script in four different waysby importing and calling its functionby passing filename commandline argumentby redirecting stdin to fileand by piping command' output to stdin by supporting importable functionscommand-line argumentsand standard streamspython system tools code can be reused in wide variety of modes redirecting streams to python objects all of the previous standard stream redirections work for programs written in any language that hook into the standard streams and rely more on the shell' command-line processor than on python itself command-line redirection syntax like filename and program is evaluated by the shellnot by python more pythonesque form of redirection can be done within scripts themselves by resetting sys stdin and sys stdout to file-like objects the main trick behind this mode is that anything that looks like file in terms of methods will work as standard stream in python the object' interface (sometimes called its protocol)and not the object' specific datatypeis all that matters that isany object that provides file-like read methods can be assigned to sys stdin to make input come from that object' read methods any object that defines file-like write methods can be assigned to sys stdoutall standard output will be sent to that object' methods because print and input simply call the write and readline methods of whatever objects sys stdout and sys stdin happen to referencewe can use this technique to both provide and intercept standard stream text with objects implemented as classes if you've already studied pythonyou probably know that such plug-and-play compatibility is usually called polymorphism--it doesn' matter what an object isand it doesn' matter what its interface doesas long as it provides the expected interface this liberal approach to datatypes accounts for much of the conciseness and flexibility of python code hereit provides way for scripts to reset their own streams example - shows utility module that demonstrates this concept example - pp \system\streams\redirect py ""file-like objects that save standard output text in string and provide standard input text from stringredirect runs passed-in function with its output and input streams reset to these file-like class objects""import sys get built-in modules class outputsimulated output file standard streams