### Start Local HTTP Server for Package Distribution Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/packaging.md Use this command to start a simple HTTP server in a directory containing your package archives. This allows package installers like pip to access your custom packages. ```console $ cd archive $ python -m http.server 9000 ``` -------------------------------- ### Install Sphinx Source: https://github.com/realpython/python-guide/blob/master/CONTRIBUTING.md Install Sphinx, the documentation generator, using pip. This command installs Sphinx for the current user. ```bash pip install --user sphinx ``` -------------------------------- ### Pipenv installation output Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Example output generated when installing packages via Pipenv. ```text Creating a Pipfile for this project... Creating a virtualenv for this project... Using base prefix '/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6' New python executable in ~/.local/share/virtualenvs/tmp-agwWamBd/bin/python3.6 Also creating executable in ~/.local/share/virtualenvs/tmp-agwWamBd/bin/python Installing setuptools, pip, wheel...done. Virtualenv location: ~/.local/share/virtualenvs/tmp-agwWamBd Installing requests... Collecting requests Using cached requests-2.18.4-py2.py3-none-any.whl Collecting idna<2.7,>=2.5 (from requests) Using cached idna-2.6-py2.py3-none-any.whl Collecting urllib3<1.23,>=1.21.1 (from requests) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests) Using cached chardet-3.0.4-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests) Using cached certifi-2017.7.27.1-py2.py3-none-any.whl Installing collected packages: idna, urllib3, chardet, certifi, requests Successfully installed certifi-2017.7.27.1 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22 Adding requests to Pipfile's [packages]... P.S. You have excellent taste! ✨ 🍰 ✨ ``` -------------------------------- ### Install Hypothesis Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Install the Hypothesis library using pip. This tool helps write parameterized tests that generate examples. ```console $ pip install hypothesis ``` -------------------------------- ### Install Salt Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/admin.md Install the Salt infrastructure management tool via pip. ```console $ pip install salt ``` -------------------------------- ### Python Test Context Setup Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md Create a `tests/context.py` file to provide import context for individual test modules. This ensures the package can be imported correctly regardless of installation method. ```default import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import sample ``` ```default from .context import sample ``` -------------------------------- ### Install Records Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/db.md Use pip to install the Records library for minimalist SQL querying. ```console $ pip install records ``` -------------------------------- ### Install ptpython Source: https://github.com/realpython/python-guide/blob/master/docs/dev/env.md Installs the ptpython REPL. ```console $ pip install ptpython ``` -------------------------------- ### Configure bbFreeze setup script Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Create a basic setup script to define the script to be frozen and the output directory. ```python from bbfreeze import Freezer freezer = Freezer(distdir='dist') freezer.addScript('foobar.py', gui_only=True) freezer() ``` -------------------------------- ### Install virtualenvwrapper Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Installation commands for virtualenvwrapper on Unix and Windows. ```console $ pip install virtualenvwrapper $ export WORKON_HOME=~/Envs $ source /usr/local/bin/virtualenvwrapper.sh ``` ```console $ pip install virtualenvwrapper-win ``` -------------------------------- ### Install Fabric Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/admin.md Use pip to install the Fabric library for system administration and deployment tasks. ```console $ pip install fabric ``` -------------------------------- ### Install BPython Source: https://github.com/realpython/python-guide/blob/master/docs/dev/env.md Installs the BPython interface for the Python interpreter. ```console $ pip install bpython ``` -------------------------------- ### Execute bbFreeze build Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Run the setup script to generate the executable distribution. ```console $ python bb_setup.py ``` -------------------------------- ### Install scikit-learn using pip Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/ml.md Use this command to install the scikit-learn library via pip. Ensure you have pip installed and updated. ```python pip install -U scikit-learn ``` -------------------------------- ### Install cryptography library Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/crypto.md Use pip to install the cryptography library. This is the first step before using its encryption features. ```console pip install cryptography ``` -------------------------------- ### Install IPython Source: https://github.com/realpython/python-guide/blob/master/docs/dev/env.md Installs the IPython interactive shell via pip. ```console $ pip install ipython ``` ```console $ pip install ipython[all] ``` -------------------------------- ### Install PugSQL Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/db.md Use pip to install the PugSQL library for organizing and using parameterized SQL. ```console $ pip install pugsql ``` -------------------------------- ### Configure Logging via INI File Source: https://github.com/realpython/python-guide/blob/master/docs/writing/logging.md Example of an INI file for configuring Python's logging module. This setup defines loggers, handlers, and formatters. ```ini [loggers] keys=root [handlers] keys=stream_handler [formatters] keys=formatter [logger_root] level=DEBUG handlers=stream_handler [handler_stream_handler] class=StreamHandler level=DEBUG formatter=formatter args=(sys.stderr,) [formatter_formatter] format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s ``` -------------------------------- ### Install Ansible Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/admin.md Install Ansible using pip. This command installs the Ansible package and its dependencies. ```console $ pip install ansible ``` -------------------------------- ### Install virtualenv Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Install the virtualenv package using pip. ```console $ pip install virtualenv ``` -------------------------------- ### Install packages with pip Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Installs a Python package into the active virtual environment. ```console $ pip install requests ``` -------------------------------- ### Install packages with Pipenv Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Use this command to install dependencies and initialize a Pipfile in your project directory. ```console $ cd project_folder $ pipenv install requests ``` -------------------------------- ### Install Pipenv Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Install Pipenv using pip with a user-level installation to avoid system-wide package conflicts. ```console $ pip install --user pipenv ``` -------------------------------- ### Manage environment dependencies Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Commands for freezing current package versions to a file and installing from that file. ```console $ pip freeze > requirements.txt ``` ```console $ pip install -r requirements.txt ``` -------------------------------- ### Verify Python Installation Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Check the installed version of Python from the command line. ```console $ python --version ``` -------------------------------- ### Install SQLAlchemy Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/db.md Use pip to install the SQLAlchemy library for database toolkit functionalities. ```console $ pip install sqlalchemy ``` -------------------------------- ### Configure Tornado Server Application Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/web.md Sets up a basic Tornado web application with a root handler and starts the I/O loop. ```python application = tornado.web.Application([ (r"/", MainHandler), ]) PORT=8884 if __name__ == "__main__": # Setup the server application.listen(PORT) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Install Python 3 using Homebrew Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/osx.md Execute this command in the terminal after setting up Homebrew and configuring your PATH to install Python 3. ```bash $ brew install python ``` -------------------------------- ### Install mock for older Python versions Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md For Python versions older than 3.3, install the 'mock' library using pip. ```console $ pip install mock ``` -------------------------------- ### Verify Pip Installation Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Check the installed version of pip from the command line. ```console $ pip --version ``` -------------------------------- ### Install Python 2.7 with Homebrew Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install/osx.md Installs Python 2.7 using the Homebrew package manager. This command assumes Homebrew is already installed and configured. ```shell $ brew install python@2 ``` -------------------------------- ### Install bbFreeze via pip Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Use this command to install the bbFreeze package in your environment. ```console $ pip install bbfreeze ``` -------------------------------- ### Verify Virtual Environment Requirement Source: https://github.com/realpython/python-guide/blob/master/docs/dev/pip-virtualenv.md Example output when attempting to use pip without an active virtual environment after configuration. ```console $ pip install requests Could not find an activated virtualenv (required). ``` -------------------------------- ### Install direnv on macOS Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Use Homebrew to install the direnv utility for automatic environment activation. ```console $ brew install direnv ``` -------------------------------- ### Unix Console Command Example Source: https://github.com/realpython/python-guide/blob/master/docs/notes/styleguide.md Format command line examples for Unix-like systems using the `console` code block and include the `$` prefix. ```console $ run command --help $ ls .. ``` -------------------------------- ### Install Python 2 on Fedora Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install/linux.md Use the dnf package manager to install Python 2 on distributions where it is not pre-installed. ```console $ sudo dnf install python2 ``` -------------------------------- ### Install Python 3 on Fedora Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/linux.md Use the dnf package manager to install Python 3 on Fedora. ```console $ sudo dnf install python3 ``` -------------------------------- ### Install py.test Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Install py.test using pip. This tool provides a no-boilerplate alternative to Python's standard unittest module. ```console $ pip install pytest ``` -------------------------------- ### Use installed packages in Python Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md A simple script demonstrating how to import and use the requests library. ```python import requests response = requests.get('https://httpbin.org/ip') print('Your IP is {0}'.format(response.json()['origin'])) ``` -------------------------------- ### Create and Start a Thread in Python Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/speed.md Use the Thread constructor to pass a callable and its arguments, then call start() to run it in a new thread. Requires importing Thread from the threading module. ```python from threading import Thread import requests def get_webpage(url): page = requests.get(url) return page some_thread = Thread(get_webpage, 'http://google.com/') some_thread.start() ``` -------------------------------- ### Install Package Directly from URL using Pip Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/packaging.md Install a package directly from its tarball URL served by a local HTTP server. This is an alternative to using an extra index URL when the package is not in a subdirectory. ```console $ pip install http://127.0.0.1:9000/MyPackage.tar.gz ``` -------------------------------- ### Install Pillow via pip Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/imaging.md Use this command to install the Pillow library for image manipulation. ```console $ pip install Pillow ``` -------------------------------- ### Install tox Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Install tox using pip. This tool automates test environment management for multiple Python interpreter configurations. ```console $ pip install tox ``` -------------------------------- ### Sample Scraped Data Output Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/scrape.md This is an example of the output after successfully scraping buyer names and prices from the web page. ```default Buyers: ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes', 'Derri Anne Connecticut', 'Moe Dess', 'Leda Doggslife', 'Dan Druff', 'Al Fresco', 'Ido Hoe', 'Howie Kisses', 'Len Lease', 'Phil Meup', 'Ira Pent', 'Ben D. Rules', 'Ave Sectomy', 'Gary Shattire', 'Bobbi Soks', 'Sheila Takya', 'Rose Tattoo', 'Moe Tell'] Prices: ['$29.95', '$8.37', '$15.26', '$19.25', '$19.25', '$13.99', '$31.57', '$8.49', '$14.47', '$15.86', '$11.11', '$15.98', '$16.27', '$7.50', '$50.85', '$14.26', '$5.68', '$15.00', '$114.07', '$10.09'] ``` -------------------------------- ### Install Python 3.8 via PPA Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/linux.md Use the deadsnakes PPA to install Python 3.8 on Ubuntu systems. ```default $ sudo apt-get install software-properties-common $ sudo add-apt-repository ppa:deadsnakes/ppa $ sudo apt-get update $ sudo apt-get install python3.8 ``` -------------------------------- ### Install Package from Local HTTP Server using Pip Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/packaging.md Install a package named 'MyPackage' from a local HTTP server running on port 9000. This command assumes your package is hosted in a subdirectory named 'MyPackage'. ```console $ pip install --extra-index-url=http://127.0.0.1:9000/ MyPackage ``` -------------------------------- ### Install Package from S3-Hosted PyPI using Pip Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/packaging.md Install a package from a personal PyPI server hosted on Amazon S3. Ensure the S3 bucket is configured with public read access for the package files. ```console pip install --index-url=http://your-s3-bucket/packages/simple/ YourPackage ``` -------------------------------- ### Install bbFreeze for Python 2.x Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Install bbFreeze using pip2 or easy_install. Note that bbFreeze is only compatible with Python 2.x and is no longer actively maintained. ```console $ pip2 install bbfreeze ``` ```console $ easy_install bbfreeze ``` -------------------------------- ### Auto-format Code with black Source: https://github.com/realpython/python-guide/blob/master/docs/writing/style.md Install and use black for opinionated, deterministic code formatting. ```console $ pip install black ``` ```console $ black optparse.py ``` -------------------------------- ### Create Windows Executable with py2exe Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Use this setup.py script to configure py2exe for creating a Windows executable. Ensure you have Python installed on Windows. ```python from distutils.core import setup import py2exe setup( windows=[{'script': 'foobar.py'}], ) ``` -------------------------------- ### Install scikit-learn using conda Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/ml.md Use this command to install the scikit-learn library via conda. This is recommended if you are using the Anaconda distribution. ```python conda install scikit-learn ``` -------------------------------- ### Configure setup.py for Packaging Source: https://context7.com/realpython/python-guide/llms.txt Standard configuration file for defining package metadata and dependencies. ```python # setup.py from setuptools import setup, find_packages setup( name='mypackage', version='0.1.0', packages=find_packages(), install_requires=[ 'requests>=2.25.0', 'click>=7.0', ], entry_points={ 'console_scripts': [ 'mycommand=mypackage.cli:main', ], }, author='Your Name', author_email='you@example.com', description='A short description', url='https://github.com/you/mypackage', classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', ], ) ``` -------------------------------- ### Verify pip installation Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/linux.md Check for the existence of pip or pip3 commands in the system path. ```console $ command -v pip ``` ```console $ command -v pip3 ``` -------------------------------- ### Django Project Initialization (Incorrect) Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md Avoid this common mistake when starting a Django project, which leads to repetitive paths and unnecessary nesting. ```default $ django-admin.py startproject samplesite ``` -------------------------------- ### Create Mako Template Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/web.md Example of a Mako template utilizing inheritance and function definitions. ```mako <%inherit file="base.html"/> <% rows = [[v for v in range(0,10)] for row in range(0,10)] %> % for row in rows: ${makerow(row)} % endfor
<%def name="makerow(row)"> % for name in row: ${name}\ % endfor ``` -------------------------------- ### Check Python 3 version Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/linux.md Verify the currently installed version of Python 3. ```console $ python3 --version ``` -------------------------------- ### Get Operating System Fact with Facter Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/admin.md Use the Facter tool to retrieve the operating system name from a system. ```console $ facter operatingsystem Ubuntu ``` -------------------------------- ### Python Interpreter Example Source: https://github.com/realpython/python-guide/blob/master/docs/notes/styleguide.md Label Python interpreter examples using `Label the example::` followed by a `code-block:: python` directive. ```python >>> import this ``` -------------------------------- ### Importing a module Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md Demonstrates the basic syntax for importing a module. ```python import library.foo_plugin ``` -------------------------------- ### Serve Documentation Locally on Specific Port and IP Source: https://github.com/realpython/python-guide/blob/master/CONTRIBUTING.md Start Python's HTTP server on a specific port and bind it to a particular IP address, such as localhost. This is useful for testing on a specific network interface. ```bash python3 -m http.server 8005 --bind 127.0.0.1 ``` -------------------------------- ### Django Project Initialization (Correct) Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md Initialize a Django project correctly by specifying the current directory with a dot (`.`) to avoid nested project structures. ```default $ django-admin.py startproject samplesite . ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/realpython/python-guide/blob/master/CONTRIBUTING.md Use Python's built-in HTTP server to view locally generated HTML documentation. This command starts a server on the default port 8000. ```bash python3 -m http.server ``` -------------------------------- ### Verify virtualenv installation Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Check the installed version of virtualenv. ```console $ virtualenv --version ``` -------------------------------- ### Makefile for Project Management Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md A sample Makefile defining generic management tasks like initialization and testing. Place Makefiles at the root of your repository. ```default init: pip install -r requirements.txt test: py.test tests .PHONY: init test ``` -------------------------------- ### Create a virtual environment Source: https://github.com/realpython/python-guide/blob/master/docs/dev/virtualenvs.md Initialize a new virtual environment folder named venv. ```console $ cd project_folder $ virtualenv venv ``` -------------------------------- ### Install NumPy for OpenCV Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/imaging.md Install the NumPy dependency required for OpenCV image processing. ```console $ pip install numpy ``` -------------------------------- ### Implement Function Decorators in Python Source: https://context7.com/realpython/python-guide/llms.txt Demonstrates manual decoration, the preferred @ syntax, and creating decorators that accept arguments. ```python # Manual decoration def foo(): return "foo" foo = decorator(foo) # Using @ syntax (preferred) @decorator def bar(): return "bar" # Decorator with arguments def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(times=3) def greet(name): print(f"Hello {name}") greet("World") # Prints greeting 3 times ``` -------------------------------- ### py.test Sample Test File Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Create test files with a simple syntax for py.test. Assertions are made using the standard assert statement. ```python # content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5 ``` -------------------------------- ### Hypothesis Falsifying Example Output Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Hypothesis reports the minimal example that caused a test to fail, aiding in debugging. ```none Falsifying example: test_mean( xs=[1.7976321109618856e+308, 6.102390043022755e+303] ) ``` -------------------------------- ### Generate Windows Executable using py2exe Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Run this command in your console after creating the setup.py file to generate the .exe file in the dist directory. ```console $ python setup.py py2exe ``` -------------------------------- ### Install PyInstaller on OS X Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Use pip to install PyInstaller, a tool for creating executables on OS X and Linux. ```console $ pip install pyinstaller ``` -------------------------------- ### Install Python 3.6 on Ubuntu Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/linux.md Commands to update package lists and install Python 3.6 on supported Ubuntu versions. ```default $ sudo apt-get update $ sudo apt-get install python3.6 ``` -------------------------------- ### Install Python 3 via Chocolatey Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/win.md Installs Python 3 on Windows systems using the Chocolatey package manager. ```doscon choco install python ``` -------------------------------- ### Define Standard Project Structure Source: https://context7.com/realpython/python-guide/llms.txt Follow this recommended repository layout for maintainable and navigable Python projects. ```text README.rst LICENSE setup.py requirements.txt sample/__init__.py sample/core.py sample/helpers.py docs/conf.py docs/index.rst tests/context.py tests/test_basic.py tests/test_advanced.py ``` -------------------------------- ### Install Homebrew Package Manager Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/osx.md Run this command in your terminal to install Homebrew, a package manager for macOS. It will prompt you before making changes. ```bash $ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" ``` -------------------------------- ### Configure Python Logging Source: https://context7.com/realpython/python-guide/llms.txt Shows how to configure logging for libraries using NullHandler and for applications using StreamHandler. ```python # In a library's __init__.py - only add NullHandler import logging logging.getLogger(__name__).addHandler(logging.NullHandler()) # Application logging - direct configuration import logging logger = logging.getLogger() handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.debug('Debug message') logger.info('Info message') logger.warning('Warning message') logger.error('Error message') ``` -------------------------------- ### Hypothesis Test Example Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Example of a Hypothesis test for lists of floats. It uses the `@given` decorator to parameterize the test with generated data. ```python @given(lists(floats(allow_nan=False, allow_infinity=False), min_size=1)) def test_mean(xs): mean = sum(xs) / len(xs) assert min(xs) <= mean(xs) <= max(xs) ``` -------------------------------- ### Python Docstring Example Source: https://github.com/realpython/python-guide/blob/master/docs/writing/documentation.md Use docstrings to describe modules, classes, and functions in Python. This example shows a basic function docstring. ```python def square_and_rooter(x): """Return the square root of self times self.""" ... ``` -------------------------------- ### Configure Logging Directly in Code Source: https://github.com/realpython/python-guide/blob/master/docs/writing/logging.md Set up logging programmatically by creating handler and formatter objects and attaching them to a logger. This offers fine-grained control over the logging setup. ```python import logging logger = logging.getLogger() handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.debug('often makes a very good meal of %s', 'visiting tourists') ``` -------------------------------- ### Python Code Example Source: https://github.com/realpython/python-guide/blob/master/docs/notes/styleguide.md Provide descriptive titles for Python code examples using `Descriptive title::` followed by a `code-block:: python` directive. ```python def get_answer(): return 42 ``` -------------------------------- ### Configure advanced bbFreeze options Source: https://github.com/realpython/python-guide/blob/master/docs/shipping/freezing.md Use include and exclude parameters to manage dependencies and file paths during the freezing process. ```python freezer = Freezer(distdir='dist', includes=['my_code'], excludes=['docs']) ``` -------------------------------- ### Install Homebrew Package Manager Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install/osx.md Installs the Homebrew package manager on Mac OS X. This script will explain changes and prompt for confirmation before proceeding. ```shell $ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ``` -------------------------------- ### Python Doctest Example Source: https://github.com/realpython/python-guide/blob/master/docs/writing/tests.md Use doctest to embed executable examples within docstrings. Ensure tests run automatically with the main test suite. ```python def square(x): """Return the square of x. >>> square(2) 4 >>> square(-2) 4 """ return x * x if __name__ == '__main__': import doctest doctest.testmod() ``` -------------------------------- ### Check Python 3 Version Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install3/osx.md Verify that Python 3 is installed and accessible by checking its version using this command. It should output the installed Python 3 version number. ```bash # Do I have a Python 3 installed? $ python --version Python 3.7.1 # Success! ``` -------------------------------- ### Create a Chef Cookbook Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/admin.md Use the knife command-line tool to create a new Chef cookbook. This command scaffolds the basic directory structure for a cookbook. ```console knife cookbook create cookbook_name ``` -------------------------------- ### Importing functions and namespaces Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md Compares different import styles to illustrate readability and namespace clarity. ```python [...] from modu import * [...] x = sqrt(4) # Is sqrt part of modu? A builtin? Defined above? ``` ```python from modu import sqrt [...] x = sqrt(4) # sqrt may be part of modu, if not redefined in between ``` ```python import modu [...] x = modu.sqrt(4) # sqrt is visibly part of modu's namespace ``` -------------------------------- ### Verify Pip Version for Python 2 Source: https://github.com/realpython/python-guide/blob/master/docs/starting/install/osx.md Checks the version of the pip package installer associated with the Homebrew-installed Python 2 interpreter. Homebrew typically installs pip alongside Setuptools. ```shell $ pip2 -V # pip pointing to the Homebrew installed Python 2 interpreter $ pip -V # pip pointing to the Homebrew installed Python 3 interpreter (if installed) ``` -------------------------------- ### Puppet Manifest for SSH Server Configuration Source: https://github.com/realpython/python-guide/blob/master/docs/scenarios/admin.md This Puppet code ensures the OpenSSH-Server package is installed and the sshd service is running. It configures the sshd_config file and notifies the sshd service to restart if the configuration file changes. The 'require' statement ensures the package is installed before the file is managed. ```puppet package { 'openssh-server': ensure => installed, } file { '/etc/ssh/sshd_config': source => 'puppet:///modules/sshd/sshd_config', owner => 'root', group => 'root', mode => '640', notify => Service['sshd'], # sshd will restart # whenever you edit this # file require => Package['openssh-server'], } service { 'sshd': ensure => running, enable => true, hasstatus => true, hasrestart=> true, } ``` -------------------------------- ### Basic File Opening with Context Manager Source: https://github.com/realpython/python-guide/blob/master/docs/writing/structure.md This is the standard way to open and read a file using a context manager, ensuring the file is automatically closed. ```python with open('file.txt') as f: contents = f.read() ``` -------------------------------- ### Apply Import Best Practices Source: https://context7.com/realpython/python-guide/llms.txt Use explicit imports and namespaces to maintain clarity and avoid naming conflicts. ```python # Very bad - unclear where sqrt comes from from modu import * x = sqrt(4) # Better - explicit import from modu import sqrt x = sqrt(4) # Best - namespace makes origin clear import modu x = modu.sqrt(4) # For deep packages, use aliases import very.deep.module as mod result = mod.some_function() # Naming modules: use short, lowercase names # OK import library.plugin.foo # Not OK - don't namespace with underscores import library.foo_plugin ```