id
int64
0
25.6k
text
stringlengths
0
4.59k
18,200
alsobe aware that the buffer size parameters only specify limit at which writes occur and do not necessarily set limit on internal resource use for examplewhen you do write(dataon buffered file fall of the bytes in data are first copied into the internal buffers if data represents very large byte arraythis copying will...
18,201
operating system services meaning as with textiowrapper an instance of stringio supports all of the usual file operationsin addition to method getvalue(that returns the current contents of the memory buffer the open(function the io module defines the following open(functionwhich is the same as the builtin open(function...
18,202
logging the logging module provides flexible facility for applications to log eventserrorswarningsand debugging information this information can be collectedfilteredwritten to filessent to the system logand even sent over the network to remote machines this section covers the essential details of using this module for ...
18,203
operating system services most of these parameters are self-explanatory the format argument is used to specify the format of log messages along with optional contextual information such as filenameslevelsline numbersand so forth datefmt is date format string compatible with the time strftime(function if omittedthe date...
18,204
or series of names separated by periods (for example 'appor 'app net'if you omit lognameyou will get the logger object associated with the root logger the creation of logger instances is different than what you find in most other library modules when you create loggeryou always give it name which is passed to getlogger...
18,205
operating system services thusif you pass single dictionary as an argumentthe format string can include dictionary key names here are few examples that illustrate how this workslog logging getlogger("app" log message using positional formatting log critical("can' connect to % at port % "hostporta log message using dict...
18,206
filtering log messages each logger object log has an internal level and filtering mechanism that determines which log messages get handled the following two methods are used to perform simple filtering based on the numeric level of log messageslog setlevel(levelsets the level of log only logging messages with level gre...
18,207
operating system services the following example illustrates how you create custom filterclass filterfunc(logging filter)def _init_ (self,name)self funcname name def filter(selfrecord)if record funcname =self funcnamereturn false elsereturn true log addfilter(filterfunc('foo')log addfilter(filterfunc('bar')ignore all me...
18,208
override the settings on the parentachieving kind of level promotion here is an exampleimport logging the top-level logger 'applog logging getlogger('app'log setlevel(logging criticalonly accept critical level messages child logger 'app netnet_log logging getlogger('app net'net_log setlevel(logging erroraccept error me...
18,209
operating system services handler objects the logging module provides collection of pre-built handlers that can process log messages in various in ways these handlers are added to logger objects using their addhandler(method in additioneach handler can be configured with its own filtering and levels built-in handlers t...
18,210
handlers rotatingfilehandler(filename [mode [maxbytes [backupcount [encoding [delay]]]]]writes log messages to the file filename howeverif the file exceeds the size specified by maxbytesthe file is rotated to filename and new log filefilenameis opened backupcount specifies the maximum number of backup files to create b...
18,211
operating system services again using the same filename these changes might occur if log file has been deleted or moved as result of log rotation operation carried out externally to the running program this handler only works on unix systems handler configuration each handler object can be configured with its own level...
18,212
describes how this extra information can be automatically added to log messages formatter objects to change the log message formatyou must first create formatter objectformatter([fmt [datefmt]]creates new formatter object fmt provides format string for messages within fmtyou can place various expansions as previously d...
18,213
operating system services log critical("could not connect to server"extra=netinfothe downside of this approach is that you have to make sure every logging operation includes the extra information or else the program will crash an alternative approach is to use the logadapter class as wrapper for an existing logger loga...
18,214
levelas appropriate create handler objects by instantiating one of the various types of handlers (filehandlerstreamhandlersockethandlerand so onand set an appropriate level create message formatter objects and attach them to the handler objects using the setformatter(method attach the handler objects to the logger obje...
18,215
operating system services dictionary of default configuration parameters for use in the config file the specified filename is read using the configparser module disable_existing_loggers is boolean flag that specifies whether or not any existing loggers are disabled when new configuration data is read by defaultthis is ...
18,216
logging config fileconfig('applogconfig ini'as beforemodules that want to issue log messages do not need to worry about the details of loading the logging configuration they merely import the logging module and get reference to the appropriate logger object for exampleimport logging app_log logging getlogger("app"app_l...
18,217
operating system services nary file or byte string is expected furthermorethe contents of memory-mapped file are mutable this means that modifications can be made using index-assignment and slice-assignment operators unless private mapping of the file has been madesuch changes directly alter the contents of the underly...
18,218
length is larger than the current size of the filethe file is extended to length bytes if length is the current length of the file is used as the length as long as the file is nonempty (otherwisean exception will be raisedtagname is an optional string that can be used to name the mapping if tagname refers to an existin...
18,219
write(stringwrites string of bytes to the file at the current file pointer write_byte(bytewrites single byte into memory at the current file pointer notes although unix and windows supply slightly different mmap(functionsthis module can be used in portable manner by relying on the optional access parameter that is comm...
18,220
kbhit(returns true if keypress is waiting to be read locking(fdmodenbyteslocks part of filegiven file descriptor from the runtime nbytes is the number of bytes to lock relative to the current file pointer mode is one of the following integerssetting description unlocks the file region (lk_unlcklocks the file region (lk...
18,221
operating system services see alsowinreg ( optparse the optparse module provides high-level support for processing unix-style command-line options supplied in sys argv simple example of using the module is found in use of optparse primarily focuses on the optionparser class optionparser([**args]creates new command opti...
18,222
unless you really need to customize option processing in some wayan optionparser will usually be created with no arguments for examplep optparse optionparser(an instancepof optionparser supports the following methodsp add_option(name namen [**parms]adds new option to the arguments name name and so on are all of the var...
18,223
operating system services keyword argument description callback_args optional positional arguments supplied to callback function specified with the callback argument optional keyword arguments supplied to callback function specified with the callback argument list of strings that specifies all possible option values us...
18,224
set_defaults(dest=valuedest=valuesets the default values of particular option destinations you simply supply keyword arguments that specify the destinations you wish to set the name of the keyword arguments should match the names specified using the dest parameter in add_option()described earlier set_usage(usagechanges...
18,225
here is short interactive unix session that shows how the previous code workspython foo py - usagefoo py [optionsoptions- --help show this help message and exit - - outfile--outfile=outfile - debug--debuglevel=debug --speed=speed --coord=coord --novice --guru python foo py - - outfile dat - --coord --speed=ludicrous bl...
18,226
the following general-purpose variables are definedenviron mapping object representing the current environment variables changes to the mapping are reflected in the current environment if the putenv(function is also availablethen changes are also reflected in subprocesses linesep the string used to separate lines on th...
18,227
operating system services getgid(returns the real group id of the process (unixgetgroups(returns list of integer group ids to which the process owner belongs (unixgetlogin(returns the user name associated with the effective user id (unixgetpgid(pidreturns the process group id of the process with process id pid if pid i...
18,228
setpgrp(creates new process group by calling the system call setpgrp(or setpgrp( )depending on which version is implemented (if anyreturns the id of the new process group (unixsetpgid(pidpgrpassigns process pid to process group pgrp if pid is equal to pgrpthe process becomes new process group leader if pid is not equal...
18,229
operating system services closerange(lowhighcloses all file descriptors fd in the range low <fd high errors are ignored dup(fdduplicates file descriptor fd returns new file descriptor that' the lowest-numbered unused file descriptor for the process the new and old file descriptors can be used interchangeably furthermor...
18,230
constant description "pc_name_max"pc_no_truncmaximum length of filename in directory indicates whether an attempt to create file with name longer than pc_name_max for directory will fail with an enametoolong error maximum length of relative path name when the directory fd is the current working directory size of the pi...
18,231
operating system services open(file [flags [mode]]opens the file file flags is the bitwise or of the following constant valuesvalue description o_rdonly o_wronly open the file for reading open the file for writing open for reading and writing (updatesappend bytes to the end of the file create the file if it doesn' exis...
18,232
mode meaning group has execute permission (stat s_ixgrpgroup has write permission (stat s_iwgrpgroup has read permission (stat s_irgrpgroup has read/write/exec permission (stat s_irwxgothers have execute permission (stat s_ixothothers have write permission (stat s_iwothothers have read permission (stat s_irothothers ha...
18,233
operating system services files and directories the following functions and variables are used to manipulate files and directories on the file system to handle variances in filenaming schemesthe following variables contain information about the construction of path namesvariable description altsep an alternative charac...
18,234
chmod(pathmodechanges the mode of path mode has the same values as described for the open(function (unix and windowschown(pathuidgidchanges the owner and group id of path to the numeric uid and gid setting uid or gid to - causes that parameter to remain unmodified (unixlchflags(pathflagsthe same as chflags()but doesn' ...
18,235
operating system services mkdir(path [mode]creates directory named path with numeric mode mode the default mode is on non-unix systemsthe mode setting may have no effect or be ignored mkfifo(path [mode]creates fifo ( named pipenamed path with numeric mode mode the default mode is (unixmknod(path [modedevice]creates dev...
18,236
attribute description st_mode st_ino st_dev st_nlink inode protection mode inode number device the inode resides on number of links to the inode user id of the owner group id of the owner file size in bytes time of last access time of last modification time of last status change st_uid st_gid st_size st_atime st_mtime ...
18,237
operating system services unlink(pathremoves the file path same as remove(utime(path(atimemtime)sets the access and modified time of the file to the given values (the second argument is tuple of two items the time arguments are specified in terms of the numbers returned by the time time(function walk(top [topdown [oner...
18,238
execve(pathargsenvexecutes new program like execv(but additionally accepts dictionaryenvthat defines the environment in which the program runs env must be dictionary mapping strings to strings execvp(pathargslike execv(pathargsbut duplicates the shell' actions in searching for an executable file in list of directories ...
18,239
operating system services forkpty(creates child process using new pseudo-terminal as the child' controlling terminal returns pair (pidfd)in which pid is in the child and fd is file descriptor of the master end of the pseudo-terminal this function is available only in certain versions of unix kill(pidsigsends the proces...
18,240
constant description p_overlay executes the program and destroys the calling process (same as the exec functionsexecutes the program and detaches from it the calling program continues to run but cannot wait for the spawned process p_detach spawnv(is available on windows and some versions of unix spawnve(modepathargsenv...
18,241
operating system services times(returns -tuple of floating-point numbers indicating accumulated times in seconds on unixthe tuple contains the user timesystem timechildren' user timechildren' system timeand elapsed real time in that order on windowsthe tuple contains the user timesystem timeand zeros for the other thre...
18,242
wifcontinued(statusreturns true if the process has resumed from job-control stop wifsignaled(statusreturns true if the process exited due to signal wifstopped(statusreturns true if the process has been stopped wstopsig(statusreturns the signal that caused the process to stop wtermsig(statusreturns the signal that cause...
18,243
operating system services parameter description "sc_tzname_maxmaximum number of bytes in time zone name "sc_open_maxmaximum number of files process can open at one time "sc_job_controlsystem supports job control "sc_saved_idsindicates whether each process has saved set-user-id and saved set-group-id urandom(nreturns st...
18,244
expanduser(pathreplaces path names of the form '~userwith user' home directory if the expansion fails or path does not begin with '~'the path is returned unmodified expandvars(pathexpands environment variables of the form '$nameor '${name}in path malformed or nonexistent variable names are left unchanged getatime(pathr...
18,245
operating system services normcase(pathnormalizes the case of path name on non-case-sensitive file systemsthis converts path to lowercase on windowsforward slashes are also converted to backslashes normpath(pathnormalizes path name this collapses redundant separators and up-level references so that ' // '' / 'and ' /fo...
18,246
note on windowssome care is required when working with filenames that include drive letter (for example' :spam txt'in most casesfilenames are interpreted as being relative to the current working directory for exampleif the current directory is ' :\foo\'then the file ' :spam txtis interpreted as the file ' :\foo\ :spam ...
18,247
operating system services itimer_virtualand sigprof is generated for itimer_prof set seconds to to clear timer returns tuple (secondsintervalwith the previous settings of the timer siginterrupt(signalnumflagsets the system call restart behavior for given signal number if flag is falsesystem calls interrupted by signal ...
18,248
signal name description sigttou sigurg sigusr sigusr control tty urgent condition user defined user defined virtual time alarm window size change cpu limit exceeded file size limit exceeded sigvtalrm sigwinch sigxcpu sigxfsz in additionthe module defines the following variablesvariable description sig_dfl sig_ign nsig ...
18,249
extreme care is needed if signals and threads are used in the same program currentlyonly the main thread of execution can set new signal handlers or receive signals signal handling on windows is of only limited functionality the number of supported signals is extremely limited on this platform subprocess the subprocess...
18,250
keyword description provides startup flags used when creating processes on windows the default value is none possible values include startf_useshowwindow and startf_usestdhandlers stderr file object representing the file to use for stderr in the child process may be file object created via open()an integer file descrip...
18,251
terminate(terminates the subprocess by sending it sigterm signal on unix or calling the win api terminateprocess function on windows wait(waits for to terminate and returns the return code pid process id of the child process returncode numeric return code of the process if nonethe process has not terminated yet if nega...
18,252
on windowspipes are opened in binary file mode thusif you are reading text output from subprocessline endings will include the extra carriage return character ('\ \ninstead of '\ 'if this is concernsupply the universal_newlines option to popen( the subprocess module can not be used to control processes that expect to b...
18,253
operating system services gmtime([secs]converts time expressed in seconds since the epoch to time in utc coordinated universal time ( greenwich mean timethis function returns struct_time object with the following attributesattribute value tm_year tm_mon tm_mday tm_hour tm_min tm_sec tm_wday tm_yday tm_isdst four-digit ...
18,254
directive meaning % % % % hour ( -hour clockas decimal number [ - day of the year as decimal number [ - month as decimal number [ - minute as decimal number [ - locale' equivalent of either am or pm seconds as decimal number [ - week number of the year [ - (sunday as first dayweekday as decimal number [ - ( sundayweek ...
18,255
the accuracy of the time functions is often much less than what might be suggested by the units in which time is represented for examplethe operating system might only update the time - times second see alsodatetime ( winreg the winreg module (_winreg in python provides low-level interface to the windows registry the r...
18,256
deletekey(keysub_keydeletes sub_key key is an open key or one of the predefined hkey_constants sub_key is string that identifies the key to delete sub_key must not have any subkeysotherwiseenvironmenterror is raised deletevalue(keyvaluedeletes named value from registry key key is an open key or one of the predefined hk...
18,257
operating system services be created with the savekey(functionand the calling process must have se_restore_ privilege for this to work if key was returned by connectregistry()filename should be path that' relative to the remote computer openkey(keysub_key[res [sam]]opens key key is an open key or an hkey_constant sub_k...
18,258
setvalue(keysub_keytypevaluesets the value of key key is an open key or hkey_constant sub_key is the name of the subkey with which to associate the value type is an integer type codecurrently limited to reg_sz value is string containing the value data if sub_key does not existit is created key must have been opened wit...
18,259
lib fl ff
18,260
threads and concurrency his describes library modules and programming strategies for writing concurrent programs in python topics include threadsmessage passingmultiprocessingand coroutines before covering specific library modulessome basic concepts are first described basic concepts running program is called process e...
18,261
threads and concurrency when multiple processes or threads are usedthe host operating system is responsible for scheduling their work this is done by giving each process (or threada small time slice and rapidly cycling between all of the active tasks--giving each portion of the available cpu cycles for exampleif your s...
18,262
even when threads are usedmany programmers find their scaling properties to be rather mysterious for examplea threaded network server that works fine with threads may have horrible performance if it' scaled up to , threads as general ruleyou really don' want to be writing programs with , threads because each thread req...
18,263
threads and concurrency process([group [target [name [args [kwargs]]]]] class that represents task running in subprocess the arguments in the constructor should always been specified using keyword arguments target is callable object that will execute when the process startsargs is tuple of positional arguments passed t...
18,264
exitcode the integer exit code of the process if the process is still runningthis is none if the value is negativea value of - means the process was terminated by signal name the name of the process pid the integer process id of the process here is an example that shows how to create and launch function (or other calla...
18,265
threads and concurrency queue([maxsize]creates shared process queue maxsize is the maximum number of items allowed in the queue if omittedthere is no size limit the underlying queue is implemented using pipes and locks in additiona support thread is launched in order to feed queued data into the underlying pipe an inst...
18,266
put_nowait(itemthe same as put(itemfalseq qsize(returns the approximate number of items currently in the queue the result of this function is not reliable because items may have been added or removed from the queue in between the time the result is returned and later used in program on some systemsthis method may raise...
18,267
threads and concurrency of generator or produced in some other manner sequence [ , , , producer(sequenceqwait for all items to be processed join(in this examplethe consumer process is set to daemonic because it runs forever and we want it to terminate when the main program finishes (if you forget thisthe program will h...
18,268
put the item on the queue output_q put(itemif _name_ =' _main_ ' multiprocessing queue(launch the consumer process cons_p multiprocessing process(target=consumer,args=( ,)cons_p start(produce items sequence [ , , , producer(sequenceqsignal completion by putting the sentinel on the queue put(nonewait for the consumer pr...
18,269
threads and concurrency recv_bytes_into(buffer [offset]receives complete byte message and stores it in the object bufferwhich supports the writable buffer interface ( bytearray object or similaroffset specifies the byte offset into the buffer where to place the message returns the number of bytes received raises buffer...
18,270
great attention should be given to proper management of the pipe endpoints if one of the ends of the pipe is not used in either the producer or consumerit should be closed this explainsfor instancewhy the output end of the pipe is closed in the producer and the input end of the pipe is closed in the consumer if you for...
18,271
threads and concurrency process pools the following class allows you to create pool of processes to which various kind of data processing tasks can be submitted the functionality provided by pool is somewhat similar to that provided by list comprehensions and functional programming operations such as map-reduce pool([n...
18,272
map_async(funciterable [chunksize [callback]]the same as map(except that the result is returned asynchronously the return value is an instance of asyncresult that can be used to later obtain the result callback is callable object accepting single argument if suppliedcallback is called with the result when it becomes av...
18,273
threads and concurrency allfiles (os path join(path,namefor pathdirsfiles in os walk(topdirfor name in filesdigest_map dict(digest_pool imap_unordered(compute_digest,allfiles, )digest_pool close(return digest_map try it out change the directory name as desired if _name_ =' _main_ 'digest_map build_digest_map("/users/be...
18,274
access its contents using the standard python indexingslicingand iteration operationseach of which are synchronized by the lock for byte stringsa will also have an value attribute to access the entire array as single string rawarray(typecodeinitializerthe same as array except that there is no locking if you are writing...
18,275
threads and concurrency performance test receive bunch of messages def consume_test(countch)for in xrange(count)values ch recv(performance test send bunch of messages def produce_test(countvaluesch)for in xrange(count)ch send(valuesif _name_ =' _main_ 'ch floatchannel( multiprocessing process(target=consume_testargs=( ...
18,276
condition([lock]creates shared threading condition instance on the server and returns proxy to it lock is proxy instance created by lock(or rlock( dict([args]creates shared dict instance on the server and returns proxy to it the arguments to this method are the same as for the built-in dict(function event(creates share...
18,277
threads and concurrency if _name_ =' _main_ ' multiprocessing manager( dict(create shared dict evt event(create shared event launch process that watches the dictionary multiprocessing process(target=watch,args=( ,evt) daemon=true start(update the dictionary and notify the watcher ['foo' evt set(time sleep( update the d...
18,278
method is not found in this mappingthe return value is copied and returned if method_to_typeid is nonethe value of proxytype _method_to_typeid_ is used if it is defined create_method is boolean flag that specifies whether method with the name typeid should be created in mgrclass by defaultthis is true an instance of ma...
18,279
threads and concurrency server firstyou will find that data attributes and properties cannot be accessed insteadyou have to use access functionsa traceback (most recent call last)file ""line in attributeerror'autoproxy[ ]object has no attribute 'xa getx( setx( with proxiesthe repr(function returns string representing t...
18,280
proxy _callmethod(name [args [kwargs]]calls the method name on the proxy' referent object name is string with the method nameargs is tuple containing positional argumentsand kwargs is dictionary of keyword arguments the method name must be explicitly exposed normally this is done by including the name in the _exposed_ ...
18,281
threads and concurrency close(closes the pipe or socket being used by the listener last_accepted the address of the last client that was accepted here is an example of server program that listens for clients and implements simple remote operation (adding)from multiprocessing connection import listener serv listener((''...
18,282
get_logger(returns the logging object associated with the multiprocessing modulecreating it if it doesn' already exist the returned logger does not propagate messages to the root loggerhas level of logging notsetand prints all logging messages to standard error set_executable(executablesets the name of the python execu...
18,283
threads and concurrency threading the threading module provides thread class and variety of synchronization primitives for writing multithreaded programs thread objects the thread class is used to represent separate thread of control new thread can be created as followsthread(group=nonetarget=nonename=noneargs=()kwargs...
18,284
thread that represents the initial thread of control and which is not daemonic in older codet setdaemon(flagand isdaemon(are used to manipulate this value here is an example that shows how to create and launch function (or other callableas threadimport threading import time def clock(interval)while trueprint("the time ...
18,285
threads and concurrency timer objectthas the following methodst start(starts the timer the function func supplied to timer(will be executed after the specified timer interval cancel(cancels the timer if the function has not executed yet lock objects primitive lock (or mutual exclusion lockis synchronization primitive t...
18,286
rlock release(releases lock by decrementing its recursion level if the recursion level is zero after the decrementthe lock is reset to the unlocked state otherwisethe lock remains locked this function should only be called by the thread that currently owns the lock semaphore and bounded semaphore semaphore is synchroni...
18,287
threads and concurrency the kind of signaling shown in this example is often instead carried out using condition variableswhich will be described shortly events events are used to communicate between threads one thread signals an "event,and one or more other threads wait for it an event instance manages an internal fla...
18,288
of an item is inexplicably delayed in the worst casethe whole program will hang due to the loss of an event signal for these types of problemsyou are better off using condition variables condition variables condition variable is synchronization primitivebuilt on top of another lock that' used when thread is interested ...
18,289
threads and concurrency def consumer()while truecv acquire(while not item_is_available()cv wait(wait for an item to show up cv release(consume_item( subtle aspect of using condition variables is that if there are multiple threads waiting on the same conditionthe notify(operation may awaken one or more of them (this beh...
18,290
thread termination and suspension threads do not have any methods for forceful termination or suspension this omission is by design and due to the intrinsic complexity of writing threaded programs for exampleif thread has acquired lockforcefully terminating or suspending it before it is able to release the lock may cau...
18,291
threads and concurrency setprofile(funcsets profile function that will be used for all threads created func is passed to sys setprofile(before each thread starts running settrace(funcsets tracing function that will be used for all threads created func is passed to sys settrace(before each thread starts running stack_si...
18,292
priorityqueue([maxsize]creates priority queue in which items are ordered from lowest to highest priority when working with this queueitems should be tuples of the form (prioritydatawhere priority is number an instance of any of the queue classes has the following methodsq qsize(returns the approximate size of the queue...
18,293
threads and concurrency import threading from queue import queue use from queue on python class workerthread(threading thread)def _init_ (self,*args,**kwargs)threading thread _init_ (self,*args,**kwargsself input_queue queue(def send(self,item)self input_queue put(itemdef close(self)self input_queue put(noneself input_...
18,294
the underlying concept that drives this programming technique is the fact that the yield statement in generator or coroutine function suspends the execution of the function until it is later resumed with next(or send(operation this makes it possible to cooperatively multitask between set of generator functions using sc...
18,295
lib fl ff
18,296
network programming and sockets his describes the modules used to implement low-level network servers and clients python provides extensive network supportranging from programming directly with sockets to working with high-level application protocols such as http to begina very brief (and admittedly terseintroduction t...
18,297
network programming and sockets service port number ftp-data ftp-control ssh telnet smtp (mailhttp (wwwpop imap https (secure www the process of establishing tcp connection involves precise sequence of steps on both the server and clientas shown in figure server client socket(socket(bind(listen(accept(wait for connecti...
18,298
udp communication is performed in similar mannerexcept that clients and servers don' establish "connectionwith each otheras shown in figure server client socket(socket(bind(bind(recvfrom(wait for data request sendto(process request response sendto(figure recvfrom(udp connection protocol the following example illustrate...
18,299
network programming and sockets an example of establishing udp connection appears in the socket module section later in this it is common for network protocols to exchange data in the form of text howevergreat attention needs to be given to text encoding in python all strings are unicode thereforeif any kind of text st...