summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/tutorial%2Fstdlib.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/tutorial%2Fstdlib.html')
-rw-r--r--devdocs/python~3.12/tutorial%2Fstdlib.html152
1 files changed, 152 insertions, 0 deletions
diff --git a/devdocs/python~3.12/tutorial%2Fstdlib.html b/devdocs/python~3.12/tutorial%2Fstdlib.html
new file mode 100644
index 00000000..0ed5b646
--- /dev/null
+++ b/devdocs/python~3.12/tutorial%2Fstdlib.html
@@ -0,0 +1,152 @@
+ <span id="tut-brieftour"></span><h1> Brief Tour of the Standard Library</h1> <section id="operating-system-interface"> <span id="tut-os-interface"></span><h2>
+<span class="section-number">10.1. </span>Operating System Interface</h2> <p>The <a class="reference internal" href="../library/os#module-os" title="os: Miscellaneous operating system interfaces."><code>os</code></a> module provides dozens of functions for interacting with the operating system:</p> <pre data-language="python">&gt;&gt;&gt; import os
+&gt;&gt;&gt; os.getcwd() # Return the current working directory
+'C:\\Python312'
+&gt;&gt;&gt; os.chdir('/server/accesslogs') # Change current working directory
+&gt;&gt;&gt; os.system('mkdir today') # Run the command mkdir in the system shell
+0
+</pre> <p>Be sure to use the <code>import os</code> style instead of <code>from os import *</code>. This will keep <a class="reference internal" href="../library/os#os.open" title="os.open"><code>os.open()</code></a> from shadowing the built-in <a class="reference internal" href="../library/functions#open" title="open"><code>open()</code></a> function which operates much differently.</p> <p id="index-0">The built-in <a class="reference internal" href="../library/functions#dir" title="dir"><code>dir()</code></a> and <a class="reference internal" href="../library/functions#help" title="help"><code>help()</code></a> functions are useful as interactive aids for working with large modules like <a class="reference internal" href="../library/os#module-os" title="os: Miscellaneous operating system interfaces."><code>os</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; import os
+&gt;&gt;&gt; dir(os)
+&lt;returns a list of all module functions&gt;
+&gt;&gt;&gt; help(os)
+&lt;returns an extensive manual page created from the module's docstrings&gt;
+</pre> <p>For daily file and directory management tasks, the <a class="reference internal" href="../library/shutil#module-shutil" title="shutil: High-level file operations, including copying."><code>shutil</code></a> module provides a higher level interface that is easier to use:</p> <pre data-language="python">&gt;&gt;&gt; import shutil
+&gt;&gt;&gt; shutil.copyfile('data.db', 'archive.db')
+'archive.db'
+&gt;&gt;&gt; shutil.move('/build/executables', 'installdir')
+'installdir'
+</pre> </section> <section id="file-wildcards"> <span id="tut-file-wildcards"></span><h2>
+<span class="section-number">10.2. </span>File Wildcards</h2> <p>The <a class="reference internal" href="../library/glob#module-glob" title="glob: Unix shell style pathname pattern expansion."><code>glob</code></a> module provides a function for making file lists from directory wildcard searches:</p> <pre data-language="python">&gt;&gt;&gt; import glob
+&gt;&gt;&gt; glob.glob('*.py')
+['primes.py', 'random.py', 'quote.py']
+</pre> </section> <section id="command-line-arguments"> <span id="tut-command-line-arguments"></span><h2>
+<span class="section-number">10.3. </span>Command Line Arguments</h2> <p>Common utility scripts often need to process command line arguments. These arguments are stored in the <a class="reference internal" href="../library/sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> module’s <em>argv</em> attribute as a list. For instance, let’s take the following <code>demo.py</code> file:</p> <pre data-language="python"># File demo.py
+import sys
+print(sys.argv)
+</pre> <p>Here is the output from running <code>python demo.py one two three</code> at the command line:</p> <pre data-language="python">['demo.py', 'one', 'two', 'three']
+</pre> <p>The <a class="reference internal" href="../library/argparse#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module provides a more sophisticated mechanism to process command line arguments. The following script extracts one or more filenames and an optional number of lines to be displayed:</p> <pre data-language="python">import argparse
+
+parser = argparse.ArgumentParser(
+ prog='top',
+ description='Show top lines from each file')
+parser.add_argument('filenames', nargs='+')
+parser.add_argument('-l', '--lines', type=int, default=10)
+args = parser.parse_args()
+print(args)
+</pre> <p>When run at the command line with <code>python top.py --lines=5 alpha.txt
+beta.txt</code>, the script sets <code>args.lines</code> to <code>5</code> and <code>args.filenames</code> to <code>['alpha.txt', 'beta.txt']</code>.</p> </section> <section id="error-output-redirection-and-program-termination"> <span id="tut-stderr"></span><h2>
+<span class="section-number">10.4. </span>Error Output Redirection and Program Termination</h2> <p>The <a class="reference internal" href="../library/sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> module also has attributes for <em>stdin</em>, <em>stdout</em>, and <em>stderr</em>. The latter is useful for emitting warnings and error messages to make them visible even when <em>stdout</em> has been redirected:</p> <pre data-language="python">&gt;&gt;&gt; sys.stderr.write('Warning, log file not found starting a new one\n')
+Warning, log file not found starting a new one
+</pre> <p>The most direct way to terminate a script is to use <code>sys.exit()</code>.</p> </section> <section id="string-pattern-matching"> <span id="tut-string-pattern-matching"></span><h2>
+<span class="section-number">10.5. </span>String Pattern Matching</h2> <p>The <a class="reference internal" href="../library/re#module-re" title="re: Regular expression operations."><code>re</code></a> module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:</p> <pre data-language="python">&gt;&gt;&gt; import re
+&gt;&gt;&gt; re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
+['foot', 'fell', 'fastest']
+&gt;&gt;&gt; re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
+'cat in the hat'
+</pre> <p>When only simple capabilities are needed, string methods are preferred because they are easier to read and debug:</p> <pre data-language="python">&gt;&gt;&gt; 'tea for too'.replace('too', 'two')
+'tea for two'
+</pre> </section> <section id="mathematics"> <span id="tut-mathematics"></span><h2>
+<span class="section-number">10.6. </span>Mathematics</h2> <p>The <a class="reference internal" href="../library/math#module-math" title="math: Mathematical functions (sin() etc.)."><code>math</code></a> module gives access to the underlying C library functions for floating point math:</p> <pre data-language="python">&gt;&gt;&gt; import math
+&gt;&gt;&gt; math.cos(math.pi / 4)
+0.70710678118654757
+&gt;&gt;&gt; math.log(1024, 2)
+10.0
+</pre> <p>The <a class="reference internal" href="../library/random#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code>random</code></a> module provides tools for making random selections:</p> <pre data-language="python">&gt;&gt;&gt; import random
+&gt;&gt;&gt; random.choice(['apple', 'pear', 'banana'])
+'apple'
+&gt;&gt;&gt; random.sample(range(100), 10) # sampling without replacement
+[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
+&gt;&gt;&gt; random.random() # random float
+0.17970987693706186
+&gt;&gt;&gt; random.randrange(6) # random integer chosen from range(6)
+4
+</pre> <p>The <a class="reference internal" href="../library/statistics#module-statistics" title="statistics: Mathematical statistics functions"><code>statistics</code></a> module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data:</p> <pre data-language="python">&gt;&gt;&gt; import statistics
+&gt;&gt;&gt; data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
+&gt;&gt;&gt; statistics.mean(data)
+1.6071428571428572
+&gt;&gt;&gt; statistics.median(data)
+1.25
+&gt;&gt;&gt; statistics.variance(data)
+1.3720238095238095
+</pre> <p>The SciPy project &lt;<a class="reference external" href="https://scipy.org">https://scipy.org</a>&gt; has many other modules for numerical computations.</p> </section> <section id="internet-access"> <span id="tut-internet-access"></span><h2>
+<span class="section-number">10.7. </span>Internet Access</h2> <p>There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are <a class="reference internal" href="../library/urllib.request#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code>urllib.request</code></a> for retrieving data from URLs and <a class="reference internal" href="../library/smtplib#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code>smtplib</code></a> for sending mail:</p> <pre data-language="python">&gt;&gt;&gt; from urllib.request import urlopen
+&gt;&gt;&gt; with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
+... for line in response:
+... line = line.decode() # Convert bytes to a str
+... if line.startswith('datetime'):
+... print(line.rstrip()) # Remove trailing newline
+...
+datetime: 2022-01-01T01:36:47.689215+00:00
+
+&gt;&gt;&gt; import smtplib
+&gt;&gt;&gt; server = smtplib.SMTP('localhost')
+&gt;&gt;&gt; server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
+... """To: jcaesar@example.org
+... From: soothsayer@example.org
+...
+... Beware the Ides of March.
+... """)
+&gt;&gt;&gt; server.quit()
+</pre> <p>(Note that the second example needs a mailserver running on localhost.)</p> </section> <section id="dates-and-times"> <span id="tut-dates-and-times"></span><h2>
+<span class="section-number">10.8. </span>Dates and Times</h2> <p>The <a class="reference internal" href="../library/datetime#module-datetime" title="datetime: Basic date and time types."><code>datetime</code></a> module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output formatting and manipulation. The module also supports objects that are timezone aware.</p> <pre data-language="python">&gt;&gt;&gt; # dates are easily constructed and formatted
+&gt;&gt;&gt; from datetime import date
+&gt;&gt;&gt; now = date.today()
+&gt;&gt;&gt; now
+datetime.date(2003, 12, 2)
+&gt;&gt;&gt; now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
+'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
+
+&gt;&gt;&gt; # dates support calendar arithmetic
+&gt;&gt;&gt; birthday = date(1964, 7, 31)
+&gt;&gt;&gt; age = now - birthday
+&gt;&gt;&gt; age.days
+14368
+</pre> </section> <section id="data-compression"> <span id="tut-data-compression"></span><h2>
+<span class="section-number">10.9. </span>Data Compression</h2> <p>Common data archiving and compression formats are directly supported by modules including: <a class="reference internal" href="../library/zlib#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code>zlib</code></a>, <a class="reference internal" href="../library/gzip#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code>gzip</code></a>, <a class="reference internal" href="../library/bz2#module-bz2" title="bz2: Interfaces for bzip2 compression and decompression."><code>bz2</code></a>, <a class="reference internal" href="../library/lzma#module-lzma" title="lzma: A Python wrapper for the liblzma compression library."><code>lzma</code></a>, <a class="reference internal" href="../library/zipfile#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code>zipfile</code></a> and <a class="reference internal" href="../library/tarfile#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a>.</p> <pre data-language="python">&gt;&gt;&gt; import zlib
+&gt;&gt;&gt; s = b'witch which has which witches wrist watch'
+&gt;&gt;&gt; len(s)
+41
+&gt;&gt;&gt; t = zlib.compress(s)
+&gt;&gt;&gt; len(t)
+37
+&gt;&gt;&gt; zlib.decompress(t)
+b'witch which has which witches wrist watch'
+&gt;&gt;&gt; zlib.crc32(s)
+226805979
+</pre> </section> <section id="performance-measurement"> <span id="tut-performance-measurement"></span><h2>
+<span class="section-number">10.10. </span>Performance Measurement</h2> <p>Some Python users develop a deep interest in knowing the relative performance of different approaches to the same problem. Python provides a measurement tool that answers those questions immediately.</p> <p>For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The <a class="reference internal" href="../library/timeit#module-timeit" title="timeit: Measure the execution time of small code snippets."><code>timeit</code></a> module quickly demonstrates a modest performance advantage:</p> <pre data-language="python">&gt;&gt;&gt; from timeit import Timer
+&gt;&gt;&gt; Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
+0.57535828626024577
+&gt;&gt;&gt; Timer('a,b = b,a', 'a=1; b=2').timeit()
+0.54962537085770791
+</pre> <p>In contrast to <a class="reference internal" href="../library/timeit#module-timeit" title="timeit: Measure the execution time of small code snippets."><code>timeit</code></a>’s fine level of granularity, the <a class="reference internal" href="../library/profile#module-profile" title="profile: Python source profiler."><code>profile</code></a> and <a class="reference internal" href="../library/profile#module-pstats" title="pstats: Statistics object for use with the profiler."><code>pstats</code></a> modules provide tools for identifying time critical sections in larger blocks of code.</p> </section> <section id="quality-control"> <span id="tut-quality-control"></span><h2>
+<span class="section-number">10.11. </span>Quality Control</h2> <p>One approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process.</p> <p>The <a class="reference internal" href="../library/doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a> module provides a tool for scanning a module and validating tests embedded in a program’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along with its results into the docstring. This improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentation:</p> <pre data-language="python">def average(values):
+ """Computes the arithmetic mean of a list of numbers.
+
+ &gt;&gt;&gt; print(average([20, 30, 70]))
+ 40.0
+ """
+ return sum(values) / len(values)
+
+import doctest
+doctest.testmod() # automatically validate the embedded tests
+</pre> <p>The <a class="reference internal" href="../library/unittest#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> module is not as effortless as the <a class="reference internal" href="../library/doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a> module, but it allows a more comprehensive set of tests to be maintained in a separate file:</p> <pre data-language="python">import unittest
+
+class TestStatisticalFunctions(unittest.TestCase):
+
+ def test_average(self):
+ self.assertEqual(average([20, 30, 70]), 40.0)
+ self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
+ with self.assertRaises(ZeroDivisionError):
+ average([])
+ with self.assertRaises(TypeError):
+ average(20, 30, 70)
+
+unittest.main() # Calling from the command line invokes all tests
+</pre> </section> <section id="batteries-included"> <span id="tut-batteries-included"></span><h2>
+<span class="section-number">10.12. </span>Batteries Included</h2> <p>Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example:</p> <ul class="simple"> <li>The <a class="reference internal" href="../library/xmlrpc.client#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code>xmlrpc.client</code></a> and <a class="reference internal" href="../library/xmlrpc.server#module-xmlrpc.server" title="xmlrpc.server: Basic XML-RPC server implementations."><code>xmlrpc.server</code></a> modules make implementing remote procedure calls into an almost trivial task. Despite the modules’ names, no direct knowledge or handling of XML is needed.</li> <li>The <a class="reference internal" href="../library/email#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages."><code>email</code></a> package is a library for managing email messages, including MIME and other <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2822.html"><strong>RFC 2822</strong></a>-based message documents. Unlike <a class="reference internal" href="../library/smtplib#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code>smtplib</code></a> and <a class="reference internal" href="../library/poplib#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code>poplib</code></a> which actually send and receive messages, the email package has a complete toolset for building or decoding complex message structures (including attachments) and for implementing internet encoding and header protocols.</li> <li>The <a class="reference internal" href="../library/json#module-json" title="json: Encode and decode the JSON format."><code>json</code></a> package provides robust support for parsing this popular data interchange format. The <a class="reference internal" href="../library/csv#module-csv" title="csv: Write and read tabular data to and from delimited files."><code>csv</code></a> module supports direct reading and writing of files in Comma-Separated Value format, commonly supported by databases and spreadsheets. XML processing is supported by the <a class="reference internal" href="../library/xml.etree.elementtree#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code>xml.etree.ElementTree</code></a>, <a class="reference internal" href="../library/xml.dom#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code>xml.dom</code></a> and <a class="reference internal" href="../library/xml.sax#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code>xml.sax</code></a> packages. Together, these modules and packages greatly simplify data interchange between Python applications and other tools.</li> <li>The <a class="reference internal" href="../library/sqlite3#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code>sqlite3</code></a> module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax.</li> <li>Internationalization is supported by a number of modules including <a class="reference internal" href="../library/gettext#module-gettext" title="gettext: Multilingual internationalization services."><code>gettext</code></a>, <a class="reference internal" href="../library/locale#module-locale" title="locale: Internationalization services."><code>locale</code></a>, and the <a class="reference internal" href="../library/codecs#module-codecs" title="codecs: Encode and decode data and streams."><code>codecs</code></a> package.</li> </ul> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/tutorial/stdlib.html" class="_attribution-link">https://docs.python.org/3.12/tutorial/stdlib.html</a>
+ </p>
+</div>