Library and Extension FAQ — Python 3.15.2 documentation
Navigation index modules | next | previous | Python » 3.15.2 documentation » Python Frequently Asked Questions » Library and Extension FAQ | Theme | Library and Extension FAQ ¶ General Library Questions ¶ How do I find a module or application to perform task X? ¶ Check the Library Reference to see if there's a relevant standard library module. (Eventually you'll learn what's in the standard library and will be able to skip this step.) For third-party packages, search the Python Package Index or try Google or another web search engine.
Searching for "Python" plus a keyword or two for your topic of interest will usually find something helpful. Where is the math.py (socket.py, regex.py, etc.) source file? ¶ If you can't find a source file for a module it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like mathmodule.c , somewhere in a C source directory (not on the Python Path).
There are (at least) three kinds of modules in Python: modules written in Python (.py); modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); modules written in C and linked with the interpreter; to get a list of these, type: import sys print ( sys . builtin_module_names ) How do I make a Python script executable on Unix? ¶ You need to do two things: the script file's mode must be executable and the first line must begin with #! followed by the path of the Python interpreter.
The first is done by executing chmod +x scriptfile or perhaps chmod 755 scriptfile . The second can be done in a number of ways. The most straightforward way is to write #!/usr/local/bin/python as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the env program.
Almost all Unix variants support the following, assuming the Python interpreter is in a directory on the user's PATH : #!/usr/bin/env python Don't do this for CGI scripts. The PATH variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user's environment is so full that the /usr/bin/env program fails; or there's no env program at all. In that case, you can try the following hack (due to Alex Rezinsky): #! /bin/sh """:" exec python $0 ${ 1 + " $@ " } """ The minor disadvantage is that this defines the script's __doc__ string.
However, you can fix that by adding __doc__ = """...Whatever...""" Is there a curses/termcap package for Python? ¶ For Unix variants: The standard Python source distribution comes with a curses module in the Modules subdirectory, though it's not compiled by default. (Note that this is not available in the Windows distribution -- there is no curses module for Windows.) The curses module supports basic curses features as well as many additional functions from ncurses and SYSV curses such as colour, alternative character set support, pads, and mouse support.
This means the module isn't compatible with operating systems that only have BSD curses, but there don't seem to be any currently maintained OSes that fall into this category. Is there an equivalent to C's onexit() in Python? ¶ The atexit module provides a register function that is similar to C's onexit() . Why don't my signal handlers work? ¶ The most common problem is that the signal handler is declared with the wrong argument list.
It is called as handler ( signum , frame ) so it should be declared with two parameters: def handler ( signum , frame ): ... Common tasks ¶ How do I test a Python program or component? ¶ Python comes with two testing frameworks. The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring. The unittest module is a fancier testing framework modelled on Java and Smalltalk testing frameworks.
To make testing easier, you should use good modular design in your program. Your program should have almost all functionality encapsulated in either functions or class methods -- and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.
The "global main logic" of your program may be as simple as if __name__ == "__main__" : main_logic () at the bottom of the main module of your program. Once your program is organized as a tractable collection of function and class behaviours, you should write test functions that exercise the behaviours. A test suite that automates a sequence of tests can be associated with each module. This sounds like a lot of work, but since Python is so terse and flexible it's surprisingly easy.
You can make coding much more pleasant and fun by writing your test functions in parallel with the "production code", since this makes it easy to find bugs and even design flaws earlier. "Support modules" that are not intended to be the main module of a program may include a self-test of the module. if __name__ == "__main__" : self_test () Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using "fake" interfaces implemented in Python.
How do I create documentation from doc strings? ¶ The pydoc module can create HTML from the doc strings in your Python source code. An alternative for creating API documentation purely from docstrings is epydoc . Sphinx can also include docstring content. How do I get a single keypress at a time? ¶ For Unix variants there are several solutions. It's straightforward to do this using curses, but curses is a fairly large module to learn.
Threads ¶ How do I program using threads? ¶ Be sure to use the threading module and not the _thread module. The threading module builds convenient abstractions on top of the low-level primitives provided by the _thread module. How do I parcel out work among a bunch of worker threads? ¶ The easiest way is to use the concurrent.futures module, especially the ThreadPoolExecutor class. Or, if you want fine control over the dispatching algorithm, you can write your own logic manually.
Use the queue module to create a queue containing a list of jobs. The Queue class maintains a list of objects and has a .put(obj) method that adds items to the queue and a .get() method to return them. The class will take care of the locking necessary to ensure that each job is handed out exactly once. Here's a trivial example: import threading , queue , time # The worker thread gets jobs off the queue. When the queue is empty, it # assumes there will be no more work and exits. # (Realistically workers will run until terminated.) def worker (): print ( 'Running worker' ) time . sleep ( 0.1 ) while True : try : arg = q . get ( block = False ) except queue .
Empty : print ( 'Worker' , threading . current_thread (), end = ' ' ) print ( 'queue empty' ) break else : print ( 'Worker' , threading . current_thread (), end = ' ' ) print ( 'running with argument' , arg ) time . sleep ( 0.5 ) # Create queue q = queue . Queue () # Start a pool of 5 workers for i in range ( 5 ): t = threading . Thread ( target = worker , name = 'worker %i ' % ( i + 1 )) t . start () # Begin adding work to the queue for i in range ( 50 ): q . put ( i ) # Give threads time to run print ( 'Main thread sleeping' ) time . sleep ( 5 ) When run, this will produce the following output: Running worker Running worker Running worker Running worker Running worker Main thread sleeping Worker <Thread(worker 1, started 130283832797456)> running with argument 0 Worker <Thread(worker 2, started 130283824404752)> running with argument 1 Worker <Thread(worker 3, started 130283816012048)
The rest of this page is on the live site.