id
int64
0
25.6k
text
stringlengths
0
4.59k
4,800
etc ctrl- to exit notice how the parent received bytes string through the pipe raw pipes normally deal in binary byte strings when their descriptors are used directly this way with the descriptor-based file tools we met in (as we saw theredescriptor read and write tools in os always return and expect byte stringsthat' ...
4,801
in parentlisten to pipe os close(pipeoutclose output side here pipein os fdopen(pipeinmake text mode input file object while trueline pipein readline()[:- blocks until data sent print('parent % got [%sat % (os getpid()linetime time())parent(this version has also been augmented to close the unused end of the pipe in eac...
4,802
anonymous pipes and threadsnot processesthis version works on windows import ostimethreading def child(pipeout)zzz while truetime sleep(zzzmsg ('spam % dzzzencode(os write(pipeoutmsgzzz (zzz+ make parent wait pipes are binary bytes send to parent goto after def parent(pipein)while trueline os read(pipein blocks until d...
4,803
that showed up in the debugger' output stream pipe in effectthe gui acted like programmer typing commands at keyboard and client to the debugger server more generallyby spawning command-line programs with streams attached by pipessystems can add new interfaces to legacy programs in factwe'll see simple example of this ...
4,804
spawn('python''pipes-testchild py''spam'fork child program print('hello from parent'mypidsys stdout flush(reply input(sys stderr write('parent got"% "\nreplyto child' stdin subvert stdio buffering from child' stdout stderr not tied to pipeprint('hello from parent'mypidsys stdout flush(reply sys stdin readline(sys stder...
4,805
in example - in child process and reads and writes standard streams to converse with it over two pipes example - pp \system\processes\pipes-testchild py import ostimesys mypid os getpid(parentpid os getppid(sys stderr write('child % of % got arg"% "\ (mypidparentpidsys argv[ ])for in range( )time sleep( make parent pro...
4,806
occur technicallyby default stdout is just line-buffered when connected to terminalbut it is fully buffered when connected to other devices such as filessocketsand the pipes used here this is why you see script' printed text in shell window immediately as it is producedbut not until the process exits or its buffer fill...
4,807
see "more on stream bufferingpty and pexpecton page thread can avoid blocking main guitoobut really just delegate the problem (the spawned thread will still be deadlockedof the options listedthe first two--manual flushes and command-line arguments--are often the simplest solutions in factbecause it is so usefulthe seco...
4,808
program the pty module is also not available on all python platforms today (most notablyit runs on cygwin but not the standard windows pythonthe pexpect packagea pure-python equivalent of the unix expect programuses pty to provide additional functionality and to handle interactions that bypass standard streams ( passwo...
4,809
in pythonnamed pipe files are created with the os mkfifo callwhich is available today on unix-like platformsincluding cygwin' python on windowsbut is not currently available in standard windows python this call creates only the external filethoughto send and receive data through fifoit must be opened and processed as i...
4,810
window only after the child is started and begins writing messages onto the fifo file[ :\pp \system\processespython pipefifo py parent got "spam at parent got "spam at parent got "spam at parent got "spam at parent got "spam at parent got "spam at parent got "spam at parent got "spam at parent got "spam at parent got "...
4,811
although sockets are one of the most commonly used ipc toolsit' impossible to fully grasp their api without also seeing its role in networking because of thatwe'll defer most of our socket coverage until we can explore their use in network scripting in this section provides brief introduction and previewso you can comp...
4,812
print('client got[% ]replyup to bytes in message if __name__ ='__main__'from threading import thread sthread thread(target=serversthread daemon true don' wait for server thread sthread start(do wait for children to exit for in range( )thread(target=clientargs=('client%si,)start(study this script' code and comments to s...
4,813
from threading import thread mode int(sys argv[ ]if mode = run server in this process server(elif mode = run client in this process client('client:process=%sos getpid()elserun client threads in process for in range( )thread(target=clientargs=('client:thread=%si,)start(let' run this script on windowstoo (againthis porta...
4,814
be transferred over socketstooby shipping the serialized byte strings produced by python' pickle module introduced in and covered in full in as we'll see in the printed output of simple script can be redirected to gui windowby connecting the script' output stream to socket on which gui is listening in nonblocking mode ...
4,815
number passed in as command-line argument example - pp \system\processes\signal py ""catch signals in pythonpass signal number as command-line arguse "kill - pidshell command to send this process signalmost signal handlers restored by python after caught (see network scripting for sigchld details)on windowssignal modul...
4,816
con : : /usr/bin/ps kill - got signal at sun mar : : kill - got signal at sun mar : : kill - [ ]killed python signal py inputs and outputs can be bit jumbled here because the process prints to the same screen used to type new shell commands to send the program signalthe kill shell command takes signal number and proces...
4,817
ctrl- to exit : : generally speakingsignals must be used with cautions not made obvious by the examples we've just seen for instancesome system calls don' react well to being interrupted by signalsand only the main thread can install signal handlers and respond to signals in multithreaded program when used wellthoughsi...
4,818
about why you may (or may notcare about this package in more specific termsalthough this module' performance may not compete with that of pure threads or process forks for some applicationsthis module offers compelling solution for manycompared to raw process forksyou gain cross-platform portability and powerful ipc to...
4,819
has no effect on the original the pickleability constraints for process arguments on windows can limit multiprocessing' scope in other contexts as well for instancein we'll find that this module doesn' directly solve the lack of portability for the os fork call for traditionally coded socket servers on windowsbecause c...
4,820
msg '%sname:%spid:%swith lockprint(msg (label__name__os getpid())if __name__ ='__main__'lock lock(whoami('function call'lockp process(target=whoamiargs=('spawned child'lock) start( join(for in range( )process(target=whoamiargs=(('run process %si)lock)start(with lockprint('main process exit 'when runthis script first ca...
4,821
and starting "python -ccommand line in the new processwhich runs special python-coded function in this package that reads and unpickles the process and invokes its run method we met pickling briefly in and we will study it further later in this book the implementation is bit more complex than thisand is prone to change...
4,822
correct let' look next at few of those tools in action ipc toolspipesshared memoryand queues while the processes created by this package can always communicate using general system-wide tools like the sockets and fifo files we met earlierthe multiprocessing module also provides portable message passing tools specifical...
4,823
pipes and queues also keep in mind that because they are pickledobjects transferred this way are effectively copied in the receiving processdirect in-place changes to mutable objectsstate won' be noticed in the sender this makes sense if you remember that this package runs independent processes with their own memory sp...
4,824
print('parent exit'wait for child exit when run on windowshere' this script' output--one child passes an object to the parentand the other both sends and receives on the same pipec:\pp \system\processesmulti py parent got['spam' 'eggs'parent got{'name''bob''spam' talker got{'ss''aa''pp''mm'parent exit this module' pipe...
4,825
vector array(' 'procsshared memoryprocess/thread safe type codes from ctypesintdouble show start value in parent process showdata('parent start'scalarvectorspawn childpass in shared memory process(target=showdataargs=('child 'scalarvector) start() join(pass in shared memory updated in parentwait for each to finish each...
4,826
scalar= + parent+ in children showdata('parent end'scalarvectorarray[ ]= + parent+ in children the following is this script' output on windows trace through this and the code to see how it runsnotice how the changed value of the global variable is not shared by the spawned processes on windowsbut passed-in value and ar...
4,827
""process class can also be subclassed just like threading threadqueue works like queue queue but for cross-processnot cross-thread ""import ostimequeue from multiprocessing import processqueue process-safe shared queue queue is pipe locks/semas class counter(process)label @def __init__(selfstartqueue)self state start ...
4,828
attribute when runthe output of the main consumer process traces its queue fetchesand the (indentedoutput of spawned child producer processes gives process ids and state :\pp \system\processesmulti py start no data no data posted[ posted[ posted[ posted[ posted[ posted[ posted[ posted[ posted[ finish if you imagine the...
4,829
tools like the os execcalls we met earlier--by spawning process portably with multiprocessing and overlaying it with new program this waywe start new independent programand effectively work around the lack of the os fork call in standard windows python this generally assumes that the new program doesn' require any reso...
4,830
finallymultiprocessing provides many more tools than these examples deployincluding conditioneventand semaphore synchronization toolsand local and remote managers that implement servers for shared object for instanceexample - demonstrates its support for pools--spawned children that work in concert on given task exampl...
4,831
we'll use often for callbacks in the gui part of this book moreoverthis differs from the threading module that is the model for this package--calls like the following which work for threads must be translated to callable and argumentsthreading thread(target=(lambdaaction( ))start(but lambdas work here converselysome be...
4,832
treatment of this module in this book for more detailsrefer to the python library manual herewe turn next to handful of additional program launching tools and wrap up of this other ways to start programs we've seen variety of ways to launch programs in this book so far--from the os forkexec combination on unixto portab...
4,833
print(resultspam eggs ham the equivalent os spawn calls achieve the same effectwith slightly more complex call signature that provides more control over the way the program is launchedos spawnv(os p_waitr' :\python \python'('python''makewords py')spam eggs ham os spawnl(os p_nowaitr' :\python \python''python''makewords...
4,834
process mode flag is taken from these predefined valuesos p_nowait and os p_nowaito the spawn functions will return as soon as the new process has been createdwith the process id as the return value available on unix and windows os p_wait the spawn functions will not return until the new process has run to completion a...
4,835
hello from child - hello from child - hello from child - main process exiting hello from child - hello from child - hello from child - hello from child - hello from child - hello from child - notice that the copies print their output in random orderand the parent program exits before all children doall of these program...
4,836
:\pp \system\mediastart ora-lp jpg :\pp \system\mediastart sousa au because the start command can run any file and command linethere is no reason it cannot also be used to start an independently running python programc:\pp \system\processesstart child py this works because python is registered to open names ending in p...
4,837
in factstart is so useful that recent python releases also include an os startfile callwhich is essentially the same as spawning dos start command with os system and works as though the named file were double-clicked the following callsfor instancehave similar effectos startfile('lp-code-readme txt'os system('start lp-...
4,838
it implements an abstract superclasslaunchmodewhich defines what it means to start python program named by shell command linebut it doesn' define how insteadits subclasses provide run method that actually starts python program according to given scheme and (optionallydefine an announce method to display program' name a...
4,839
methods instead of if/elif logic def run(selfcmdline)assert false'run must be definedclass system(launchmode)""run python script named in shell command line caveatmay block callerunless added on unix ""def run(selfcmdline)cmdline fixwindowspath(cmdlineos system('% % (pypathcmdline)class popen(launchmode)""run shell com...
4,840
forward slashes are okay here ""def run(selfcmdline)os spawnv(os p_detachpypath(pyfilecmdline)class top_level(launchmode)""run in new windowsame process tbdrequires gui class info too ""def run(selfcmdline)assert false'sorry mode not yet implementedpick "bestlauncher for this platform may need to specialize the choice ...
4,841
method--so that the classes in this module can also be used to generate callback handlers in tkinter-based guis as we'll see in the upcoming button-presses in tkinter invoke callable object with no argumentsby registering portablelauncher instance to handle the press eventwe can automatically start new program from ano...
4,842
also notice how some of the classes in this example use the sys executable path string to obtain the python executable' full path name this is partly due to their role in userfriendly demo launchers in prior versions that predated sys executablethese classes instead called two functions exported by module named launche...
4,843
tools in the python library don' appear in this book at all with hundreds of library modulesmore appearing all the timeand even more in the third-party domainpython book authors have to pick and choose their topics frugallyas alwaysbe sure to browse the python library manuals and web early and often in your python care...
4,844
complete system programs "the greps of wraththis wraps up our look at the system interfaces domain in python by presenting collection of larger python scripts that do real systems work--comparing and copying directory treessplitting filessearching files and directoriestesting other programsconfiguring launched programs...
4,845
quickwhat' the biggest python source file on your computerthis was the query innocently posed by student in one of my python classes because didn' know eitherit became an official exercise in subsequent classesand it provides good example of ways to apply python system tools for realistic purpose in this book reallythe...
4,846
:\pp \system\filetoolsbigpy-dir py [( \\__init__ py')( \\testargv py')[( \\testargv py')( \\more py')scanning the standard library tree the prior section' solution worksbut it' obviously partial answer--python files are usually located in more than one directory even within the standard librarythere are many subdirecto...
4,847
sure enough--the prior section' script found smallest and largest files in subdirectories while searching python' entire standard library tree this way is more inclusiveit' still incompletethere may be additional modules installed elsewhere on your computerwhich are accessible from the module import search path but out...
4,848
pprint pprint(allsizes[- :]when runthis script marches down the module import path andfor each valid directory it containsattempts to search the entire tree rooted there in factit nests loops three deep--for items on the pathdirectories in the item' treeand files in the directory because the module path may contain dir...
4,849
tree as you can seethe results for largest files differ when viewed by size and lines- disparity which we'll probably have to hash out in our next requirements meeting scanning the entire machine finallyalthough searching trees rooted in the module import path normally includes every python source file you can import o...
4,850
if fixname in visitedif tracetryprint('skipping thisdirelsevisited add(fixnamefor filename in fileshereif filename endswith(extname)if trace tryprint('+++filenamefullname os path join(thisdirfilenametrybytesize os path getsize(fullnamelinesize sum(+ for line in open(fullname'rb')except exceptionprint('error'exc_info()[...
4,851
[( \\processes\\multi py')( \\filetools\\split py')( \\tester\\tester py')by lines [( \\__init__ py')( \\filetools\\__init__ py')( \\streams\\hello-out py')[( \\filetools\\split py')( \\processes\\multi py')( \\tester\\tester py')this script also lets us scan for different file typeshere it is picking out the smallest ...
4,852
:\cygwin\cygdrive :\cygwin\dev :\cygwin\dev\mqueue :\cygwin\dev\shm :\cygwin\etc many more lines omitted by bytes [( ' :\\cygwin\\\python \\python-\\lib\\build_class py')( ' :\\cygwin\\\python \\python-\\lib\\email\\mime\\__init__ py')( ' :\\cygwin\\\python \\python-\\lib\\email\\test\\__init__ py')[( ' :\\python \\lib...
4,853
error entirely this demonstrates subtle but pragmatically important issuepython ' unicode orientation extends to filenameseven if they are just printed as we learned in because filenames may contain arbitrary textos listdir returns filenames in two different ways--we get back decoded unicode strings when we pass in nor...
4,854
' :\\py \\futureproofpython pythoninfo wiki_filesb' :\\py \\oakwinter_com code \xbb porting setuptools to py k_filesb' :\\py \\what\ new in python \ python documentationfor (dirsubsfilesin os walk(root)print(dir encode() ' :\\py ' :\\py \\futureproofpython pythoninfo wiki_filesb' :\\py \\oakwinter_com code \xc \xbb por...
4,855
no room for further exploration herethoughwe'll have to be satisfied with the fact that our exception handler sidesteps the printing problem altogether you should still be aware of the implications of unicode filename decodingthoughon some platforms you may need to pass byte strings to os walk in this script to prevent...
4,856
sorts of different machines in the housethoughwe needed more portable solution splitting files portably since all the computers in my house ran pythona simple portable python script came to the rescue the python program in example - distributes single file' contents among set of part files and stores those part files i...
4,857
if len(sys argv= and sys argv[ ='-help'print('usesplit py [file-to-split target-dir [chunksize]]'elseif len(sys argv interactive true fromfile input('file to be split'input if clicked todir input('directory to store part files'elseinteractive false fromfiletodir sys argv[ : args in cmdline if len(sys argv= chunksize in...
4,858
: am , , part : am , , part : am , , part : am , , part : am , , part : am , , part : am , , part : am , part file( , , bytes dir( , , , bytes free each of these generated part files represents one binary chunk of the file python- msi-- chunk small enough to fit comfortably on floppy disk of the time in factif you add ...
4,859
manually closing files this script also goes out of its way to manually close its files as we also saw in we can often get by with single lineopen(partname'wb'write(chunkthis shorter form relies on the fact that the current python implementation automatically closes files for you when file objects are reclaimed ( when ...
4,860
output open(tofile'wb'parts os listdir(fromdirparts sort(for filename in partsfilepath os path join(fromdirfilenamefileobj open(filepath'rb'while truefilebytes fileobj read(readsizeif not filebytesbreak output write(filebytesfileobj close(output close(if __name__ ='__main__'if len(sys argv= and sys argv[ ='-help'print(...
4,861
joining :\temp\pysplit to make :\temp\mypy msi join completesee :\temp\mypy msi :\tempdir msi more : am , , mypy msi : pm , , python- msi file( , , bytes dir( , , , bytes free :\tempfc / mypy msi python- msi comparing files mypy msi and python- msi fcno differences encountered the join script simply uses os listdir to ...
4,862
string formatting expression ('part% 'to make sure that filenames all have the same number of digits at the end (fourwhen sortedthe leading zero characters in small numbers guarantee that part files are ordered for joining correctly alternativelywe could strip off digits in filenamesconvert them with intand sort numeri...
4,863
directory containing part filesc:\temp\parts name of file to be recreatedc:\temp\morepy msi joining :\temp\parts to make :\temp\morepy msi join completesee :\temp\morepy msi press enter key because these scripts package their core logic in functionsthoughit' just as easy to reuse their code by importing and calling fro...
4,864
splitting :\temp\python- msi to :\temp\tempsplit by split finished parts are in :\temp\tempsplit :\tempdir tempsplit more directory of :\temp\tempsplit : pm : pm : pm , part : pm , part : pm , part : pm , part : pm , part more lines omitted : pm , part : pm , part : pm , part : pm , part : pm , part file( , , bytes dir...
4,865
: pm , part : pm , part : pm , part : pm , part : pm , part file( , , bytes dir( , , , bytes free finallythe splitter is also smart enough to create the output directory if it doesn' yet exist and to clear out any old files there if it does exist--the followingfor exampleleaves only new files in the output directory be...
4,866
up with such an ispthere is not much recourse but to change providersand that often implies change of web addresses ss imaginethoughthat you are an 'reilly author and have published your website' address in multiple books sold widely all over the world what do you do when your isp' service level requires site changenot...
4,867
please click on the new address to jump to this pageand update any links accordingly you will be redirectly shortly to fully understand this templateyou have to know something about htmla web page description language that we'll explore in part iv but for the purposes of this exampleyou can ignore most of this file and...
4,868
filetext filetext replace('$home$'homedirfiletext filetext replace('$file$'filenameopen(fwdname' 'write(filetextcount + insert text and write file varies print('last file =>\ 'filetextsep=''print('done:'count'forward files created 'notice that the template' text is loaded by reading fileit would work just as well to co...
4,869
creating xlate-lp html as :\temp\isp-forward\xlate-lp html creating zopeoutline htm as :\temp\isp-forward\zopeoutline htm last file =site redirection pagezopeoutline htm this page has moved this page now lives at this addressplease click on the new address to jump to this pageand update any links accordingly you will b...
4,870
how much manual labor python can automate the next section provides another prime example regression test script mistakes happen as we've seenpython provides interfaces to variety of system servicesalong with tools for adding others example - shows some of the more commonly used system tools in action it implements sim...
4,871
print('-'* for arg in argsprint(argdef quiet(*args)pass trace quiet glob scripts to be tested testpatt os path join(testdir'scripts''py'testfiles glob glob(testpatttestfiles sort(trace(os getcwd()*testfilesnumfail for testpath in testfilestestname os path basename(testpathrun all tests in dir strip directory path get i...
4,872
numfail + open(outpathbad'wb'write(outdataconsider both failure can get status+stderr save output to view elif not os path exists(outpathor forcegenprint('generating:'outpathopen(outpath'wb'write(outdatacreate first output elsepriorout open(outpath'rb'read(if priorout =outdataprint('passed:'testnameelsenumfail + print(...
4,873
would trigger failure when the test is later fixed!here' first runc:\pp \system\testerpython tester py start testermon feb : : in :\users\mark\stuff\books\ \pp \dev\examples\pp \system\tester generating\outputs\test-basic-args out generating\outputs\test-basic-stdout out generating\outputs\test-basic-streams out genera...
4,874
test-basic-args in test-basic-streams in :\pp \system\testerdir / outputs test-basic-args out test-basic-stdout out test-basic-streams out test-basic-this out test-errors-runtime out bad test-errors-syntax out bad test-status-bad out bad test-status-good out :\pp \system\testerdir / errors test-errors-runtime err test-...
4,875
stderrand the second is its stdout generated up to the point where the error occurredthese are for human (or other toolsinspectionand are automatically removed the next time the tester script runsc:\pp \system\testertype errors\test-errors-runtime err traceback (most recent call last)file \scripts\test-errors-runtime p...
4,876
:\pp \system\testertype outputs\test-basic-stdout out bad begin spamspam!spamspam!spam!spamspam!spam!spam!spamend one last usage noteif you change the trace variable in this script to be verboseyou'll get much more output designed to help you trace the programs operation (but probably too much for real testing runs) :\...
4,877
parses out and reruns tests from an interactive session log that is pasted into module' docstrings the logs give test calls and expected resultsdoctest essentially reruns the interactive session see the python library manualthe pypi websiteand your favorite web search engine for additional testing toolkits in both pyth...
4,878
say the leastthere may be some magical windows setting to work around this featurebut gave up hunting for one as soon as realized that it would be easier to code copier in python the cpall py script in example - is one way to do it with this scripti control what happens when bad files are found-- can skip over them wit...
4,879
pathto os path join(dirtofilenameextend both paths if not os path isdir(pathfrom)copy simple files tryif verbose print('copying'pathfrom'to'pathtocopyfile(pathfrompathtofcount + exceptprint('error copying'pathfrom'to'pathto'--skipped'print(sys exc_info()[ ]sys exc_info()[ ]elseif verboseprint('copying dir'pathfrom'to'p...
4,880
print('copied'fcount'files,'dcount'directories'end='print('in'time clock(start'seconds'this script implements its own recursive tree traversal logic and keeps track of both the "fromand "todirectory paths as it goes at every levelit copies over simple filescreates directories in the "topathand recurs into subdirectorie...
4,881
the time wrote this edition in this test run copied tree of , files and directories in seconds on my woefully underpowered netbook machine (the builtin time clock call is used to query the system time in seconds)it may run arbitrarily faster or slower for you stillthis is at least as fast as the best drag-and-drop 've ...
4,882
in order here finding directory differences before we start codingthe first thing we need to clarify is what it means to compare two directory trees if both trees have exactly the same branch structure and depththis problem reduces to comparing corresponding files in each tree in generalthoughthe trees can have arbitra...
4,883
return all items in seq onlya set(seq set(seq would work toobut sets are randomly orderedso any platform-dependent directory order would be lost ""return [item for item in seq if item not in seq def comparedirs(dir dir files =nonefiles =none)""compare directory contentsbut not actual filesmay need bytes listdir arg for...
4,884
media moreplus py files unique to more pyc spam txt tester __init__ pyc the unique function is the heart of this scriptit performs simple list difference operation when applied to directoriesunique items represent tree differencesand common items are names of files or subdirectories that merit further comparisons or tr...
4,885
""compare all subdirectories and files in two directory treesuses binary files to prevent unicode decoding and endline transformsas trees might contain arbitrary binary files as well as arbitrary textmay need bytes listdir arg for undecodable filenames on some platforms ""compare file name lists print('- names os listd...
4,886
print('= if not diffsprint('no diffs found 'elseprint('diffs found:'len(diffs)for diff in diffsprint('-'diffchanges diffs in-place walkreport diffs list at each directory in the treethis script simply runs the dirdiff tool to detect unique namesand then compares names in common by intersecting directory lists it uses r...
4,887
since we've already studied the tree-walking tools this script employslet' jump right into few example runs when run on identical treesstatus messages scroll during the traversaland no diffs found message appears at the endc:\pp \system\filetoolsdiffall py :\temp\pp \examples copytemp diffs txt :\pp \system\filetoolsty...
4,888
firstand then search for the strings "diffand "uniquein the report' text if need more information about the differences summarizedthis interface could be much more user-friendlyof coursebut it does the job for mec:\pp \system\filetoolsdiffall py :\temp\pp \examples copytemp diff txt :\pp \system\filetoolsnotepad diff t...
4,889
copytemp\pp \system\filetools\commands py added line breaks and tabs in few of these output lines to make them fit on this pagebut the report is simple to understand in tree with , files and directorieswe found five differences--the three files we changed by editsand the two directories we threw out of sync with the th...
4,890
bigext-tree py matches bigpy-dir py matches more output omitted =======================================diffs found files differ at :\writing-backups\feb- - \dev\ch doc :\users\mark\stuff\books\ \pp \dev\ch doc files differ at :\writing-backups\feb- - \dev\ch doc :\users\mark\stuff\books\ \pp \dev\ch doc files differ at...
4,891
edit the files or run the file-comparison command on the host platform ( fc on windows/dosdiff or cmp on unix and linuxthat' not portable solution for this last stepbut for my purposesjust finding the differences in , -file tree was much more critical than reporting which lines differ in files flagged in the report of ...
4,892
if ac !bcprint(irepr(ac)repr(bc)print(repr( [ - : + ])print(repr( [ - : + ])break '\ '\ 're>\ \ndef min(*args):\ \ tmp list(arg're>\ \ndef min(*args):\ tmp list(argsapparentlyi wound up with unix line end at one point in the local copy and dos line end in the version downloaded--the combined effect of the text mode use...
4,893
operationsto custom tree walkersto general-purpose frameworks in this and the next sectionwe'll explore each option in turnjust as did while refining solutions to this real-world dilemma greps and globs and finds if you work on unix-like systemsyou probably already know that there is standard way to search files for st...
4,894
the current directory that mention the string popenfind -name "py-print -exec fgrep popen {\if you happen to have unix-like find command on every machine you will ever usethis is one way to process directories rolling your own find module but if you don' happen to have unix find on all your computersnot to worry--it' e...
4,895
import sys namepatternstartdir sys argv[ ]sys argv[ for name in find(namepatternstartdir)print(namethere' not much to this file--it' largely just minor extension to os walk--but calling its find function provides the same utility as both the deprecated find standard library module and the unix utility of the same name ...
4,896
directory specificationc:\pp \toolsfind py [qx]py :\temp\pp :\temp\pp \examples\pp \database\sqlscripts\querydb py :\temp\pp \examples\pp \gui\tools\queuetest-gui-class py :\temp\pp \examples\pp \gui\tools\queuetest-gui py :\temp\pp \examples\pp \gui\tour\quitter py :\temp\pp \examples\pp \internet\other\grail\question...
4,897
to platform-specific directory tree listing shell commands such as dir / / on dos and windows since all files match "*"this just exhaustively generates all the file names in tree with single traversal because we can usually run such shell commands in python script with os popenthe following do the same workbut the firs...
4,898
all the bytecode files in tree because these are not always portable across major python releasesit' usually good idea to ship programs without them and let python create new ones on first imports now that we're expert os walk userswe could cut out the middleman and use it directly example - codes portable and general ...
4,899
now that we also know about find operationswriting scripts based upon them is almost trivial when we just need to match filenames example - for instancefalls back on spawning shell find commands if you have them example - pp \tools\cleanpyc-find-shell py ""find and delete all "pycbytecode files at and below the directo...