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 \previ...
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_sh...
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...
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 ac...
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 givin...
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 t...
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 functio...
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...
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 i...
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 pri...
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 givera...
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...
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 ...
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 databas...
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-...
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 ...
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 conver...
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 pronea...
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 thi...
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 ...
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...
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 re...
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 pa...
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 va...
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"com...
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 ...
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...
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 bey...
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 to...
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 ne...
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 recor...
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 print...
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 exam...
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 an...
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 su...
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 - c...
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 libraryincl...
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 secti...
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 ...
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 &>e...
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 ...
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(** ' =shrubberyexpressionke...
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 ...
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 up...
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 ...
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...
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 o...
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 looki...
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...
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 ...
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 li...
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 y...
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 i...
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)...
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...
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...
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\nc...
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 t...
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 sho...
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 ...
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 writ...
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 mo...
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 tutori...
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 in...
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 configur...
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 pyth...
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 ca...
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''...
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 curren...
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 spl...
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...
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...
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 ...
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...
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 ...
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...
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 ...
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...
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 wra...
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 s...
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 al...
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 ne...
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 i...
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 ...
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 co...
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 unifo...
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 spawn...
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' ' :...
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 p...
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 ...
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'...
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__'in...
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 redirec...
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 pr...
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\strea...
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...
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 ...
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 l...
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 int...
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 streamspy...