1:tocdepth: 2 2 3========================= 4Library and Extension FAQ 5========================= 6 7.. only:: html 8 9 .. contents:: 10 11General Library Questions 12========================= 13 14How do I find a module or application to perform task X? 15-------------------------------------------------------- 16 17Check :ref:`the Library Reference <library-index>` to see if there's a relevant 18standard library module. (Eventually you'll learn what's in the standard 19library and will be able to skip this step.) 20 21For third-party packages, search the `Python Package Index 22<https://pypi.org>`_ or try `Google <https://www.google.com>`_ or 23another web search engine. Searching for "Python" plus a keyword or two for 24your topic of interest will usually find something helpful. 25 26 27Where is the math.py (socket.py, regex.py, etc.) source file? 28------------------------------------------------------------- 29 30If you can't find a source file for a module it may be a built-in or 31dynamically loaded module implemented in C, C++ or other compiled language. 32In this case you may not have the source file or it may be something like 33:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path). 34 35There are (at least) three kinds of modules in Python: 36 371) modules written in Python (.py); 382) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); 393) modules written in C and linked with the interpreter; to get a list of these, 40 type:: 41 42 import sys 43 print(sys.builtin_module_names) 44 45 46How do I make a Python script executable on Unix? 47------------------------------------------------- 48 49You need to do two things: the script file's mode must be executable and the 50first line must begin with ``#!`` followed by the path of the Python 51interpreter. 52 53The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755 54scriptfile``. 55 56The second can be done in a number of ways. The most straightforward way is to 57write :: 58 59 #!/usr/local/bin/python 60 61as the very first line of your file, using the pathname for where the Python 62interpreter is installed on your platform. 63 64If you would like the script to be independent of where the Python interpreter 65lives, you can use the :program:`env` program. Almost all Unix variants support 66the following, assuming the Python interpreter is in a directory on the user's 67:envvar:`PATH`:: 68 69 #!/usr/bin/env python 70 71*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is 72often very minimal, so you need to use the actual absolute pathname of the 73interpreter. 74 75Occasionally, a user's environment is so full that the :program:`/usr/bin/env` 76program fails; or there's no env program at all. In that case, you can try the 77following hack (due to Alex Rezinsky): 78 79.. code-block:: sh 80 81 #! /bin/sh 82 """:" 83 exec python $0 ${1+"$@"} 84 """ 85 86The minor disadvantage is that this defines the script's __doc__ string. 87However, you can fix that by adding :: 88 89 __doc__ = """...Whatever...""" 90 91 92 93Is there a curses/termcap package for Python? 94--------------------------------------------- 95 96.. XXX curses *is* built by default, isn't it? 97 98For Unix variants: The standard Python source distribution comes with a curses 99module in the :source:`Modules` subdirectory, though it's not compiled by default. 100(Note that this is not available in the Windows distribution -- there is no 101curses module for Windows.) 102 103The :mod:`curses` module supports basic curses features as well as many additional 104functions from ncurses and SYSV curses such as colour, alternative character set 105support, pads, and mouse support. This means the module isn't compatible with 106operating systems that only have BSD curses, but there don't seem to be any 107currently maintained OSes that fall into this category. 108 109For Windows: use `the consolelib module 110<http://effbot.org/zone/console-index.htm>`_. 111 112 113Is there an equivalent to C's onexit() in Python? 114------------------------------------------------- 115 116The :mod:`atexit` module provides a register function that is similar to C's 117:c:func:`onexit`. 118 119 120Why don't my signal handlers work? 121---------------------------------- 122 123The most common problem is that the signal handler is declared with the wrong 124argument list. It is called as :: 125 126 handler(signum, frame) 127 128so it should be declared with two parameters:: 129 130 def handler(signum, frame): 131 ... 132 133 134Common tasks 135============ 136 137How do I test a Python program or component? 138-------------------------------------------- 139 140Python comes with two testing frameworks. The :mod:`doctest` module finds 141examples in the docstrings for a module and runs them, comparing the output with 142the expected output given in the docstring. 143 144The :mod:`unittest` module is a fancier testing framework modelled on Java and 145Smalltalk testing frameworks. 146 147To make testing easier, you should use good modular design in your program. 148Your program should have almost all functionality 149encapsulated in either functions or class methods -- and this sometimes has the 150surprising and delightful effect of making the program run faster (because local 151variable accesses are faster than global accesses). Furthermore the program 152should avoid depending on mutating global variables, since this makes testing 153much more difficult to do. 154 155The "global main logic" of your program may be as simple as :: 156 157 if __name__ == "__main__": 158 main_logic() 159 160at the bottom of the main module of your program. 161 162Once your program is organized as a tractable collection of function and class 163behaviours, you should write test functions that exercise the behaviours. A 164test suite that automates a sequence of tests can be associated with each module. 165This sounds like a lot of work, but since Python is so terse and flexible it's 166surprisingly easy. You can make coding much more pleasant and fun by writing 167your test functions in parallel with the "production code", since this makes it 168easy to find bugs and even design flaws earlier. 169 170"Support modules" that are not intended to be the main module of a program may 171include a self-test of the module. :: 172 173 if __name__ == "__main__": 174 self_test() 175 176Even programs that interact with complex external interfaces may be tested when 177the external interfaces are unavailable by using "fake" interfaces implemented 178in Python. 179 180 181How do I create documentation from doc strings? 182----------------------------------------------- 183 184The :mod:`pydoc` module can create HTML from the doc strings in your Python 185source code. An alternative for creating API documentation purely from 186docstrings is `epydoc <http://epydoc.sourceforge.net/>`_. `Sphinx 187<http://sphinx-doc.org>`_ can also include docstring content. 188 189 190How do I get a single keypress at a time? 191----------------------------------------- 192 193For Unix variants there are several solutions. It's straightforward to do this 194using curses, but curses is a fairly large module to learn. 195 196.. XXX this doesn't work out of the box, some IO expert needs to check why 197 198 Here's a solution without curses:: 199 200 import termios, fcntl, sys, os 201 fd = sys.stdin.fileno() 202 203 oldterm = termios.tcgetattr(fd) 204 newattr = termios.tcgetattr(fd) 205 newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO 206 termios.tcsetattr(fd, termios.TCSANOW, newattr) 207 208 oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) 209 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) 210 211 try: 212 while True: 213 try: 214 c = sys.stdin.read(1) 215 print("Got character", repr(c)) 216 except OSError: 217 pass 218 finally: 219 termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) 220 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) 221 222 You need the :mod:`termios` and the :mod:`fcntl` module for any of this to 223 work, and I've only tried it on Linux, though it should work elsewhere. In 224 this code, characters are read and printed one at a time. 225 226 :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical 227 mode. :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags 228 and modify them for non-blocking mode. Since reading stdin when it is empty 229 results in an :exc:`OSError`, this error is caught and ignored. 230 231 .. versionchanged:: 3.3 232 *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3 233 :exc:`IOError` is alias for :exc:`OSError`. 234 235 236Threads 237======= 238 239How do I program using threads? 240------------------------------- 241 242Be sure to use the :mod:`threading` module and not the :mod:`_thread` module. 243The :mod:`threading` module builds convenient abstractions on top of the 244low-level primitives provided by the :mod:`_thread` module. 245 246 247None of my threads seem to run: why? 248------------------------------------ 249 250As soon as the main thread exits, all threads are killed. Your main thread is 251running too quickly, giving the threads no time to do any work. 252 253A simple fix is to add a sleep to the end of the program that's long enough for 254all the threads to finish:: 255 256 import threading, time 257 258 def thread_task(name, n): 259 for i in range(n): 260 print(name, i) 261 262 for i in range(10): 263 T = threading.Thread(target=thread_task, args=(str(i), i)) 264 T.start() 265 266 time.sleep(10) # <---------------------------! 267 268But now (on many platforms) the threads don't run in parallel, but appear to run 269sequentially, one at a time! The reason is that the OS thread scheduler doesn't 270start a new thread until the previous thread is blocked. 271 272A simple fix is to add a tiny sleep to the start of the run function:: 273 274 def thread_task(name, n): 275 time.sleep(0.001) # <--------------------! 276 for i in range(n): 277 print(name, i) 278 279 for i in range(10): 280 T = threading.Thread(target=thread_task, args=(str(i), i)) 281 T.start() 282 283 time.sleep(10) 284 285Instead of trying to guess a good delay value for :func:`time.sleep`, 286it's better to use some kind of semaphore mechanism. One idea is to use the 287:mod:`queue` module to create a queue object, let each thread append a token to 288the queue when it finishes, and let the main thread read as many tokens from the 289queue as there are threads. 290 291 292How do I parcel out work among a bunch of worker threads? 293--------------------------------------------------------- 294 295The easiest way is to use the :mod:`concurrent.futures` module, 296especially the :mod:`~concurrent.futures.ThreadPoolExecutor` class. 297 298Or, if you want fine control over the dispatching algorithm, you can write 299your own logic manually. Use the :mod:`queue` module to create a queue 300containing a list of jobs. The :class:`~queue.Queue` class maintains a 301list of objects and has a ``.put(obj)`` method that adds items to the queue and 302a ``.get()`` method to return them. The class will take care of the locking 303necessary to ensure that each job is handed out exactly once. 304 305Here's a trivial example:: 306 307 import threading, queue, time 308 309 # The worker thread gets jobs off the queue. When the queue is empty, it 310 # assumes there will be no more work and exits. 311 # (Realistically workers will run until terminated.) 312 def worker(): 313 print('Running worker') 314 time.sleep(0.1) 315 while True: 316 try: 317 arg = q.get(block=False) 318 except queue.Empty: 319 print('Worker', threading.current_thread(), end=' ') 320 print('queue empty') 321 break 322 else: 323 print('Worker', threading.current_thread(), end=' ') 324 print('running with argument', arg) 325 time.sleep(0.5) 326 327 # Create queue 328 q = queue.Queue() 329 330 # Start a pool of 5 workers 331 for i in range(5): 332 t = threading.Thread(target=worker, name='worker %i' % (i+1)) 333 t.start() 334 335 # Begin adding work to the queue 336 for i in range(50): 337 q.put(i) 338 339 # Give threads time to run 340 print('Main thread sleeping') 341 time.sleep(5) 342 343When run, this will produce the following output: 344 345.. code-block:: none 346 347 Running worker 348 Running worker 349 Running worker 350 Running worker 351 Running worker 352 Main thread sleeping 353 Worker <Thread(worker 1, started 130283832797456)> running with argument 0 354 Worker <Thread(worker 2, started 130283824404752)> running with argument 1 355 Worker <Thread(worker 3, started 130283816012048)> running with argument 2 356 Worker <Thread(worker 4, started 130283807619344)> running with argument 3 357 Worker <Thread(worker 5, started 130283799226640)> running with argument 4 358 Worker <Thread(worker 1, started 130283832797456)> running with argument 5 359 ... 360 361Consult the module's documentation for more details; the :class:`~queue.Queue` 362class provides a featureful interface. 363 364 365What kinds of global value mutation are thread-safe? 366---------------------------------------------------- 367 368A :term:`global interpreter lock` (GIL) is used internally to ensure that only one 369thread runs in the Python VM at a time. In general, Python offers to switch 370among threads only between bytecode instructions; how frequently it switches can 371be set via :func:`sys.setswitchinterval`. Each bytecode instruction and 372therefore all the C implementation code reached from each instruction is 373therefore atomic from the point of view of a Python program. 374 375In theory, this means an exact accounting requires an exact understanding of the 376PVM bytecode implementation. In practice, it means that operations on shared 377variables of built-in data types (ints, lists, dicts, etc) that "look atomic" 378really are. 379 380For example, the following operations are all atomic (L, L1, L2 are lists, D, 381D1, D2 are dicts, x, y are objects, i, j are ints):: 382 383 L.append(x) 384 L1.extend(L2) 385 x = L[i] 386 x = L.pop() 387 L1[i:j] = L2 388 L.sort() 389 x = y 390 x.field = y 391 D[x] = y 392 D1.update(D2) 393 D.keys() 394 395These aren't:: 396 397 i = i+1 398 L.append(L[-1]) 399 L[i] = L[j] 400 D[x] = D[x] + 1 401 402Operations that replace other objects may invoke those other objects' 403:meth:`__del__` method when their reference count reaches zero, and that can 404affect things. This is especially true for the mass updates to dictionaries and 405lists. When in doubt, use a mutex! 406 407 408Can't we get rid of the Global Interpreter Lock? 409------------------------------------------------ 410 411.. XXX link to dbeazley's talk about GIL? 412 413The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's 414deployment on high-end multiprocessor server machines, because a multi-threaded 415Python program effectively only uses one CPU, due to the insistence that 416(almost) all Python code can only run while the GIL is held. 417 418Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive 419patch set (the "free threading" patches) that removed the GIL and replaced it 420with fine-grained locking. Adam Olsen recently did a similar experiment 421in his `python-safethread <https://code.google.com/archive/p/python-safethread>`_ 422project. Unfortunately, both experiments exhibited a sharp drop in single-thread 423performance (at least 30% slower), due to the amount of fine-grained locking 424necessary to compensate for the removal of the GIL. 425 426This doesn't mean that you can't make good use of Python on multi-CPU machines! 427You just have to be creative with dividing the work up between multiple 428*processes* rather than multiple *threads*. The 429:class:`~concurrent.futures.ProcessPoolExecutor` class in the new 430:mod:`concurrent.futures` module provides an easy way of doing so; the 431:mod:`multiprocessing` module provides a lower-level API in case you want 432more control over dispatching of tasks. 433 434Judicious use of C extensions will also help; if you use a C extension to 435perform a time-consuming task, the extension can release the GIL while the 436thread of execution is in the C code and allow other threads to get some work 437done. Some standard library modules such as :mod:`zlib` and :mod:`hashlib` 438already do this. 439 440It has been suggested that the GIL should be a per-interpreter-state lock rather 441than truly global; interpreters then wouldn't be able to share objects. 442Unfortunately, this isn't likely to happen either. It would be a tremendous 443amount of work, because many object implementations currently have global state. 444For example, small integers and short strings are cached; these caches would 445have to be moved to the interpreter state. Other object types have their own 446free list; these free lists would have to be moved to the interpreter state. 447And so on. 448 449And I doubt that it can even be done in finite time, because the same problem 450exists for 3rd party extensions. It is likely that 3rd party extensions are 451being written at a faster rate than you can convert them to store all their 452global state in the interpreter state. 453 454And finally, once you have multiple interpreters not sharing any state, what 455have you gained over running each interpreter in a separate process? 456 457 458Input and Output 459================ 460 461How do I delete a file? (And other file questions...) 462----------------------------------------------------- 463 464Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see 465the :mod:`os` module. The two functions are identical; :func:`~os.unlink` is simply 466the name of the Unix system call for this function. 467 468To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one. 469``os.makedirs(path)`` will create any intermediate directories in ``path`` that 470don't exist. ``os.removedirs(path)`` will remove intermediate directories as 471long as they're empty; if you want to delete an entire directory tree and its 472contents, use :func:`shutil.rmtree`. 473 474To rename a file, use ``os.rename(old_path, new_path)``. 475 476To truncate a file, open it using ``f = open(filename, "rb+")``, and use 477``f.truncate(offset)``; offset defaults to the current seek position. There's 478also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where 479*fd* is the file descriptor (a small integer). 480 481The :mod:`shutil` module also contains a number of functions to work on files 482including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and 483:func:`~shutil.rmtree`. 484 485 486How do I copy a file? 487--------------------- 488 489The :mod:`shutil` module contains a :func:`~shutil.copyfile` function. Note 490that on MacOS 9 it doesn't copy the resource fork and Finder info. 491 492 493How do I read (or write) binary data? 494------------------------------------- 495 496To read or write complex binary data formats, it's best to use the :mod:`struct` 497module. It allows you to take a string containing binary data (usually numbers) 498and convert it to Python objects; and vice versa. 499 500For example, the following code reads two 2-byte integers and one 4-byte integer 501in big-endian format from a file:: 502 503 import struct 504 505 with open(filename, "rb") as f: 506 s = f.read(8) 507 x, y, z = struct.unpack(">hhl", s) 508 509The '>' in the format string forces big-endian data; the letter 'h' reads one 510"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the 511string. 512 513For data that is more regular (e.g. a homogeneous list of ints or floats), 514you can also use the :mod:`array` module. 515 516.. note:: 517 518 To read and write binary data, it is mandatory to open the file in 519 binary mode (here, passing ``"rb"`` to :func:`open`). If you use 520 ``"r"`` instead (the default), the file will be open in text mode 521 and ``f.read()`` will return :class:`str` objects rather than 522 :class:`bytes` objects. 523 524 525I can't seem to use os.read() on a pipe created with os.popen(); why? 526--------------------------------------------------------------------- 527 528:func:`os.read` is a low-level function which takes a file descriptor, a small 529integer representing the opened file. :func:`os.popen` creates a high-level 530file object, the same type returned by the built-in :func:`open` function. 531Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to 532use ``p.read(n)``. 533 534 535.. XXX update to use subprocess. See the :ref:`subprocess-replacements` section. 536 537 How do I run a subprocess with pipes connected to both input and output? 538 ------------------------------------------------------------------------ 539 540 Use the :mod:`popen2` module. For example:: 541 542 import popen2 543 fromchild, tochild = popen2.popen2("command") 544 tochild.write("input\n") 545 tochild.flush() 546 output = fromchild.readline() 547 548 Warning: in general it is unwise to do this because you can easily cause a 549 deadlock where your process is blocked waiting for output from the child 550 while the child is blocked waiting for input from you. This can be caused 551 by the parent expecting the child to output more text than it does or 552 by data being stuck in stdio buffers due to lack of flushing. 553 The Python parent can of course explicitly flush the data it sends to the 554 child before it reads any output, but if the child is a naive C program it 555 may have been written to never explicitly flush its output, even if it is 556 interactive, since flushing is normally automatic. 557 558 Note that a deadlock is also possible if you use :func:`popen3` to read 559 stdout and stderr. If one of the two is too large for the internal buffer 560 (increasing the buffer size does not help) and you ``read()`` the other one 561 first, there is a deadlock, too. 562 563 Note on a bug in popen2: unless your program calls ``wait()`` or 564 ``waitpid()``, finished child processes are never removed, and eventually 565 calls to popen2 will fail because of a limit on the number of child 566 processes. Calling :func:`os.waitpid` with the :data:`os.WNOHANG` option can 567 prevent this; a good place to insert such a call would be before calling 568 ``popen2`` again. 569 570 In many cases, all you really need is to run some data through a command and 571 get the result back. Unless the amount of data is very large, the easiest 572 way to do this is to write it to a temporary file and run the command with 573 that temporary file as input. The standard module :mod:`tempfile` exports a 574 :func:`~tempfile.mktemp` function to generate unique temporary file names. :: 575 576 import tempfile 577 import os 578 579 class Popen3: 580 """ 581 This is a deadlock-safe version of popen that returns 582 an object with errorlevel, out (a string) and err (a string). 583 (capturestderr may not work under windows.) 584 Example: print(Popen3('grep spam','\n\nhere spam\n\n').out) 585 """ 586 def __init__(self,command,input=None,capturestderr=None): 587 outfile=tempfile.mktemp() 588 command="( %s ) > %s" % (command,outfile) 589 if input: 590 infile=tempfile.mktemp() 591 open(infile,"w").write(input) 592 command=command+" <"+infile 593 if capturestderr: 594 errfile=tempfile.mktemp() 595 command=command+" 2>"+errfile 596 self.errorlevel=os.system(command) >> 8 597 self.out=open(outfile,"r").read() 598 os.remove(outfile) 599 if input: 600 os.remove(infile) 601 if capturestderr: 602 self.err=open(errfile,"r").read() 603 os.remove(errfile) 604 605 Note that many interactive programs (e.g. vi) don't work well with pipes 606 substituted for standard input and output. You will have to use pseudo ttys 607 ("ptys") instead of pipes. Or you can use a Python interface to Don Libes' 608 "expect" library. A Python extension that interfaces to expect is called 609 "expy" and available from http://expectpy.sourceforge.net. A pure Python 610 solution that works like expect is `pexpect 611 <https://pypi.org/project/pexpect/>`_. 612 613 614How do I access the serial (RS232) port? 615---------------------------------------- 616 617For Win32, OSX, Linux, BSD, Jython, IronPython: 618 619 https://pypi.org/project/pyserial/ 620 621For Unix, see a Usenet post by Mitch Chapman: 622 623 https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com 624 625 626Why doesn't closing sys.stdout (stdin, stderr) really close it? 627--------------------------------------------------------------- 628 629Python :term:`file objects <file object>` are a high-level layer of 630abstraction on low-level C file descriptors. 631 632For most file objects you create in Python via the built-in :func:`open` 633function, ``f.close()`` marks the Python file object as being closed from 634Python's point of view, and also arranges to close the underlying C file 635descriptor. This also happens automatically in ``f``'s destructor, when 636``f`` becomes garbage. 637 638But stdin, stdout and stderr are treated specially by Python, because of the 639special status also given to them by C. Running ``sys.stdout.close()`` marks 640the Python-level file object as being closed, but does *not* close the 641associated C file descriptor. 642 643To close the underlying C file descriptor for one of these three, you should 644first be sure that's what you really want to do (e.g., you may confuse 645extension modules trying to do I/O). If it is, use :func:`os.close`:: 646 647 os.close(stdin.fileno()) 648 os.close(stdout.fileno()) 649 os.close(stderr.fileno()) 650 651Or you can use the numeric constants 0, 1 and 2, respectively. 652 653 654Network/Internet Programming 655============================ 656 657What WWW tools are there for Python? 658------------------------------------ 659 660See the chapters titled :ref:`internet` and :ref:`netdata` in the Library 661Reference Manual. Python has many modules that will help you build server-side 662and client-side web systems. 663 664.. XXX check if wiki page is still up to date 665 666A summary of available frameworks is maintained by Paul Boddie at 667https://wiki.python.org/moin/WebProgramming\ . 668 669Cameron Laird maintains a useful set of pages about Python web technologies at 670http://phaseit.net/claird/comp.lang.python/web_python. 671 672 673How can I mimic CGI form submission (METHOD=POST)? 674-------------------------------------------------- 675 676I would like to retrieve web pages that are the result of POSTing a form. Is 677there existing code that would let me do this easily? 678 679Yes. Here's a simple example that uses :mod:`urllib.request`:: 680 681 #!/usr/local/bin/python 682 683 import urllib.request 684 685 # build the query string 686 qs = "First=Josephine&MI=Q&Last=Public" 687 688 # connect and send the server a path 689 req = urllib.request.urlopen('http://www.some-server.out-there' 690 '/cgi-bin/some-cgi-script', data=qs) 691 with req: 692 msg, hdrs = req.read(), req.info() 693 694Note that in general for percent-encoded POST operations, query strings must be 695quoted using :func:`urllib.parse.urlencode`. For example, to send 696``name=Guy Steele, Jr.``:: 697 698 >>> import urllib.parse 699 >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'}) 700 'name=Guy+Steele%2C+Jr.' 701 702.. seealso:: :ref:`urllib-howto` for extensive examples. 703 704 705What module should I use to help with generating HTML? 706------------------------------------------------------ 707 708.. XXX add modern template languages 709 710You can find a collection of useful links on the `Web Programming wiki page 711<https://wiki.python.org/moin/WebProgramming>`_. 712 713 714How do I send mail from a Python script? 715---------------------------------------- 716 717Use the standard library module :mod:`smtplib`. 718 719Here's a very simple interactive mail sender that uses it. This method will 720work on any host that supports an SMTP listener. :: 721 722 import sys, smtplib 723 724 fromaddr = input("From: ") 725 toaddrs = input("To: ").split(',') 726 print("Enter message, end with ^D:") 727 msg = '' 728 while True: 729 line = sys.stdin.readline() 730 if not line: 731 break 732 msg += line 733 734 # The actual mail send 735 server = smtplib.SMTP('localhost') 736 server.sendmail(fromaddr, toaddrs, msg) 737 server.quit() 738 739A Unix-only alternative uses sendmail. The location of the sendmail program 740varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes 741``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's 742some sample code:: 743 744 import os 745 746 SENDMAIL = "/usr/sbin/sendmail" # sendmail location 747 p = os.popen("%s -t -i" % SENDMAIL, "w") 748 p.write("To: receiver@example.com\n") 749 p.write("Subject: test\n") 750 p.write("\n") # blank line separating headers from body 751 p.write("Some text\n") 752 p.write("some more text\n") 753 sts = p.close() 754 if sts != 0: 755 print("Sendmail exit status", sts) 756 757 758How do I avoid blocking in the connect() method of a socket? 759------------------------------------------------------------ 760 761The :mod:`select` module is commonly used to help with asynchronous I/O on 762sockets. 763 764To prevent the TCP connect from blocking, you can set the socket to non-blocking 765mode. Then when you do the :meth:`socket.connect`, you will either connect immediately 766(unlikely) or get an exception that contains the error number as ``.errno``. 767``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't 768finished yet. Different OSes will return different values, so you're going to 769have to check what's returned on your system. 770 771You can use the :meth:`socket.connect_ex` method to avoid creating an exception. It will 772just return the errno value. To poll, you can call :meth:`socket.connect_ex` again later 773-- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this 774socket to :meth:`select.select` to check if it's writable. 775 776.. note:: 777 The :mod:`asyncio` module provides a general purpose single-threaded and 778 concurrent asynchronous library, which can be used for writing non-blocking 779 network code. 780 The third-party `Twisted <https://twistedmatrix.com/trac/>`_ library is 781 a popular and feature-rich alternative. 782 783 784Databases 785========= 786 787Are there any interfaces to database packages in Python? 788-------------------------------------------------------- 789 790Yes. 791 792Interfaces to disk-based hashes such as :mod:`DBM <dbm.ndbm>` and :mod:`GDBM 793<dbm.gnu>` are also included with standard Python. There is also the 794:mod:`sqlite3` module, which provides a lightweight disk-based relational 795database. 796 797Support for most relational databases is available. See the 798`DatabaseProgramming wiki page 799<https://wiki.python.org/moin/DatabaseProgramming>`_ for details. 800 801 802How do you implement persistent objects in Python? 803-------------------------------------------------- 804 805The :mod:`pickle` library module solves this in a very general way (though you 806still can't store things like open files, sockets or windows), and the 807:mod:`shelve` library module uses pickle and (g)dbm to create persistent 808mappings containing arbitrary Python objects. 809 810 811Mathematics and Numerics 812======================== 813 814How do I generate random numbers in Python? 815------------------------------------------- 816 817The standard module :mod:`random` implements a random number generator. Usage 818is simple:: 819 820 import random 821 random.random() 822 823This returns a random floating point number in the range [0, 1). 824 825There are also many other specialized generators in this module, such as: 826 827* ``randrange(a, b)`` chooses an integer in the range [a, b). 828* ``uniform(a, b)`` chooses a floating point number in the range [a, b). 829* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution. 830 831Some higher-level functions operate on sequences directly, such as: 832 833* ``choice(S)`` chooses a random element from a given sequence. 834* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly. 835 836There's also a ``Random`` class you can instantiate to create independent 837multiple random number generators. 838