### Install bitmath Source: https://github.com/timlnx/bitmath/blob/master/README.rst Clone the repository and install the bitmath library using pip. ```bash git clone https://github.com/timlnx/bitmath.git pip install ./bitmath ``` -------------------------------- ### Install bitmath on Fedora/EPEL Source: https://github.com/timlnx/bitmath/blob/master/README.rst Install the bitmath package on Fedora and EPEL systems using dnf. ```bash sudo dnf install python3-bitmath ``` -------------------------------- ### argparse Integration Example Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/index.md Example demonstrating how to use bitmath as an argparse type. ```APIDOC ## `argparse` Integration ### Description This example shows how to integrate bitmath with Python's `argparse` module, allowing command-line arguments to be parsed directly into bitmath objects. ### Method Define a custom type function for `argparse` that uses `bitmath.parse_string()`. ### Request Example ```python import argparse import bitmath def BitmathType(value): try: return bitmath.parse_string(value) except ValueError: raise argparse.ArgumentTypeError( f"{value!r} is not a recognized bitmath unit string" ) parser = argparse.ArgumentParser() parser.add_argument('--block-size', type=BitmathType, required=True) args = parser.parse_args(['--block-size', '10MiB']) print(args.block_size) # Output: 10.0 MiB ``` ``` -------------------------------- ### Example Click Command Run Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/integration_examples.md Demonstrates successful and error cases for the custom bitmath click parameter type. ```bash $ python script.py --block-size 10MiB Block size: 10.0 MiB In KiB: 10240.00 KiB $ python script.py --block-size bad Error: Invalid value for '--block-size': 'bad' is not a recognized bitmath unit string (examples: 10MiB, 1.5GiB, 500kB) ``` -------------------------------- ### Install bitmath using pip Source: https://github.com/timlnx/bitmath/blob/master/README.rst Install the bitmath package using pip for typical Python projects. ```bash pip install bitmath ``` -------------------------------- ### Example Test Suite Output Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/contributing.md This is an example of the output you might see when running the test suite locally. It includes sections for unique test case checking, virtual environment creation, unit test execution, and code coverage reporting. ```console ############################################# # Running Unique TestCase checker ############################################# ./tests/test_unique_testcase_names.sh ############################################# # Creating a virtualenv ############################################# ... (dependency installation) ... ############################################# # Running Unit Tests ############################################# ============================= test session starts ============================== tests/test_arithmetic.py::TestArithmetic::test_add_bitmath_to_bitmath PASSED [ 0%] tests/test_arithmetic.py::TestArithmetic::test_sub_bitmath_from_bitmath PASSED [ 0%] ... (hundreds more) ... ================================ tests coverage ================================ Name Stmts Miss Cover Missing ------------------------------------- TOTAL 623 0 100% ======================== NNN passed in Xs ======================== ``` -------------------------------- ### Example Progressbar2 Run Output Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/integration_examples.md Shows the expected output of the simulated download with the custom data transfer speed widget. ```text Downloading: |####################| 100% 18.32 MiB/s ETA: 0:00:00 ``` -------------------------------- ### Run Full CI Pipeline Locally Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/contributing.md Execute the complete continuous integration pipeline, including virtual environment setup, dependency installation, unique test name checks, the full pytest suite with coverage, and code style checks. This is the recommended command to run before opening a pull request. ```bash $ make ci ``` -------------------------------- ### Example of Accessing Multiple Instance Attributes Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Demonstrates accessing various attributes like bits, bytes, value, bin, and binary on a GB instance. ```python >>> dvd_capacity = GB(4.7) >>> print("Capacity in bits: %s\nbytes: %s\n" % \ (dvd_capacity.bits, dvd_capacity.bytes)) Capacity in bits: 37600000000.0 bytes: 4700000000.0 >>> dvd_capacity.value 4.7 >>> dvd_capacity.bin '0b100011000001001000100111100000000000' >>> dvd_capacity.binary '0b100011000001001000100111100000000000' ``` -------------------------------- ### Using bitmath.sum() for normalized results Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Use `bitmath.sum()` when you need the result normalized to a specific unit, regardless of input types. Without a `start` argument, it accumulates into `bitmath.Byte`. Pass `start` to choose a different accumulator unit. ```python >>> bitmath.sum([bitmath.MiB(1), bitmath.GiB(1)]) Byte(1074790400.0) ``` ```python >>> bitmath.sum([bitmath.KiB(1), bitmath.KiB(2)], start=bitmath.MiB(0)) MiB(0.0029296875) ``` ```python >>> bitmath.sum([bitmath.MiB(100), bitmath.KiB(2000)], start=bitmath.GiB(0)) GiB(0.0995635986328125) ``` -------------------------------- ### Example Commit Message Format Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/contributing.md Follow this format for commit messages to ensure clarity and consistency. Use imperative mood for the summary line. ```default Short summary (50 chars or less) More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. Write your commit message in the imperative: "Fix bug" and not "Fixed bug" or "Fixes bug." - Bullet points are okay, too ``` -------------------------------- ### Display Transfer Rate in Human-Readable Format Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Use the `best_prefix()` method to automatically select the most appropriate unit for displaying transfer rates, making them easier for users to understand. This example iterates through transfer rates and prints them using the default string representation of a Bit instance. ```python >>> for _rate in tx_rate(): ... print("Rate: %s/second" % Bit(_rate)) ... time.sleep(1) Rate: 100.0 b/sec Rate: 24000.0 b/sec Rate: 1024.0 b/sec Rate: 60151.0 b/sec Rate: 33.0 b/sec Rate: 9999.0 b/sec Rate: 9238742.0 b/sec Rate: 2.09895849555e+13 b/sec Rate: 934098021.0 b/sec Rate: 934894.0 b/sec ``` -------------------------------- ### argparse Integration Source: https://github.com/timlnx/bitmath/blob/master/README.rst Example of using bitmath as a custom type for argparse arguments. ```APIDOC ## argparse Integration ### Description This section demonstrates how to integrate `bitmath` with Python's `argparse` module by creating a custom argument type that can parse bitmath strings. ### Method ```python import argparse import bitmath def BitmathType(value): try: return bitmath.parse_string(value) except ValueError: raise argparse.ArgumentTypeError( f"{value!r} is not a recognized bitmath unit string" ) parser = argparse.ArgumentParser() parser.add_argument('--block-size', type=BitmathType, required=True) args = parser.parse_args(['--block-size', '10MiB']) print(args.block_size) ``` ### Request Example ```python >>> import argparse >>> import bitmath >>> >>> def BitmathType(value): ... try: ... return bitmath.parse_string(value) ... except ValueError: ... raise argparse.ArgumentTypeError( ... f"{value!r} is not a recognized bitmath unit string" ... ) ... >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--block-size', type=BitmathType, required=True) >>> args = parser.parse_args(['--block-size', '10MiB']) >>> print(args.block_size) # 10.0 MiB 10.0 MiB ``` ``` -------------------------------- ### Parse Various Size Formats Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md This example demonstrates parsing a list of different input formats, including numbers, numeric strings, and strings with units. It highlights which inputs can be parsed successfully and which result in a ValueError. ```python >>> import bitmath >>> sizes = [ 1337, 1337.7, "1337", "1337.7", "1337 B", "1337B" ] >>> for size in sizes: ... try: ... print("Parsed size into %s" % bitmath.parse_string(size).best_prefix()) ... except ValueError: ... print("Could not parse input: %s" % size) ... Could not parse input: 1337 Could not parse input: 1337.7 Could not parse input: 1337 Could not parse input: 1337.7 Parsed size into 1.3056640625 KiB Parsed size into 1.3056640625 KiB ``` -------------------------------- ### Get File Size with bitmath.getsize() Source: https://github.com/timlnx/bitmath/blob/master/README.rst Use bitmath.getsize() to retrieve the size of a file. Ensure the file path is correctly specified. ```python >>> print(bitmath.getsize('python-bitmath.spec')) 3.7060546875 KiB ``` -------------------------------- ### List Directory Contents with bitmath.listdir Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md Iterate over files in a directory and get their sizes as bitmath instances. Supports absolute paths, relative paths, and glob filtering. Use `os.walk()` with `bitmath.getsize()` for newer Python versions. ```python >>> import bitmath >>> # Default: absolute paths, Byte instances >>> for path, size in bitmath.listdir('./some_files'): ... print(path, size) /tmp/some_files/first_file Byte(1337.0) /tmp/some_files/deeper_files/second_file Byte(13370.0) ``` ```python >>> # Relative paths >>> for path, size in bitmath.listdir('./some_files', relpath=True): ... print(path, size) some_files/first_file Byte(1337.0) some_files/deeper_files/second_file Byte(13370.0) ``` ```python >>> # Filter by glob >>> for path, size in bitmath.listdir('./some_files', glob='second*'): ... print(path, size) /tmp/some_files/deeper_files/second_file Byte(13370.0) ``` ```python >>> # Sum all results >>> sizes = [size for _, size in bitmath.listdir('./some_files')] >>> print(sum(sizes).best_prefix()) 14.3623046875 KiB ``` -------------------------------- ### Get File Size Directly with bitmath.getsize() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/real_life_examples.md Simplify file size retrieval by using bitmath.getsize(), which reads the file size directly into a bitmath object. Requires importing os and bitmath. ```python import os import bitmath these_files = os.listdir('.') for f in these_files: print("%s - %s" % (f, bitmath.getsize(f))) ``` -------------------------------- ### Initializing bitmath Classes Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/classes.md Demonstrates the four acceptable ways to instantiate a bitmath class, showing initialization using default value, explicit value, bytes, or bits. ```APIDOC ## Initializing bitmath Classes ### Description This section details how to instantiate the various bitmath classes. You can initialize a class by providing its value directly, specifying the value in bytes, or providing the exact number of bits. ### Parameters - **value** (*int*) - Optional - The value of the instance in prefix units. Defaults to 0. - **bytes** (*int*) - Optional - The value of the instance as measured in bytes. - **bits** (*int*) - Optional - The value of the instance as measured in bits. ### Raises - **ValueError** - If more than one initialization parameter (value, bytes, bits) is provided. ### Request Example ```python >>> import bitmath # Omitting all keyword arguments defaults to 'value' behavior. >>> a = bitmath.KiB(1) # This is equivalent to the previous statement >>> b = bitmath.KiB(value=1) # We can also specify the initial value in bytes. # Recall, 1KiB = 1024 bytes >>> c = bitmath.KiB(bytes=1024) # Finally, we can specify exact number of bits in the # instance. Recall, 1024B = 8192b >>> d = bitmath.KiB(bits=8192) >>> a == b == c == d True ``` ``` -------------------------------- ### Initialize bitmath Classes Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/classes.md Demonstrates the four acceptable ways to instantiate a bitmath class: by value (default), by value explicitly, by bytes, or by bits. All methods result in an equivalent object. ```python >>> import bitmath # Omitting all keyword arguments defaults to 'value' behavior. >>> a = bitmath.KiB(1) # This is equivalent to the previous statement >>> b = bitmath.KiB(value=1) # We can also specify the initial value in bytes. # Recall, 1KiB = 1024 bytes >>> c = bitmath.KiB(bytes=1024) # Finally, we can specify exact number of bits in the # instance. Recall, 1024B = 8192b >>> d = bitmath.KiB(bits=8192) >>> a == b == c == d True ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/contributing.md Builds the project's HTML documentation using Sphinx. The output will be located in `docsite/build/html/`. You can view the documentation by opening the `index.html` file directly or by using the `make viewdocs` target. ```bash make docs ``` -------------------------------- ### Format All Instance Attributes Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Demonstrates how to format all attributes of a bitmath instance using a custom string. Note how attributes can be referenced multiple times. ```python >>> longer_format = """Formatting attributes for %s ...: This instances prefix unit is {unit}, which is a {system} type unit ...: The unit value is {value} ...: This value can be truncated to just 1 digit of precision: {value:.1f} ...: In binary this looks like: {binary} ...: The prefix unit is derived from a base of {base} ...: Which is raised to the power {power} ...: There are {bytes} bytes in this instance ...: The instance is {bits} bits large ...: bytes/bits without trailing decimals: {bytes:.0f}/{bits:.0f}""" % str(ugly_number) >>> print(ugly_number.format(longer_format)) ``` -------------------------------- ### bitmath.getsize() Source: https://github.com/timlnx/bitmath/blob/master/README.rst Gets the size of a file and returns it as a bitmath object. ```APIDOC ## bitmath.getsize() ### Description Gets the size of a file and returns it as a bitmath object. ### Method ```python bitmath.getsize(filename: str) ``` ### Parameters #### Path Parameters - **filename** (str) - Required - The path to the file. ### Request Example ```python >>> print(bitmath.getsize('python-bitmath.spec')) 3.7060546875 KiB ``` ``` -------------------------------- ### Instance Property Comparisons Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Illustrates comparing a bitmath instance with its equivalent in a different unit using instance properties (e.g., one_mib.kb). ```python >>> from bitmath import * >>> one_mib = MiB(1) >>> one_mib == one_mib.kb True >>> print(one_mib, one_mib.kb, one_mib.MiB) 1.0 MiB 8388.608 kb 1.0 MiB >>> six_TB = TB(6) >>> print(six_TB, six_TB.Bit) 6.0 TB 4.8e+13 b >>> six_TB == six_TB.Bit True ``` -------------------------------- ### bitmath.getsize() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/index.md Gets the size of a file. Accepts a file path or a file-like object. ```APIDOC ## bitmath.getsize() ### Description Gets the size of a file. Accepts a file path or a file-like object. ### Method `bitmath.getsize(path_or_file_object)` ### Parameters #### Path Parameters - **path_or_file_object** (str or file-like object) - Required - The path to the file or a file-like object. ### Request Example ```python >>> import bitmath >>> print(bitmath.getsize('python-bitmath.spec')) 3.7060546875 KiB ``` ``` -------------------------------- ### Accessing Instance Attributes - Power Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Gets the mathematical power to which the unit's base is raised for this instance. ```python >>> b = bitmath.Byte(1337) >>> print(b.power) 0 ``` -------------------------------- ### Initialize bitmath instance from another instance (Pure Python) Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/classes.md Demonstrates initializing a bitmath instance with a value derived from another instance's byte count. This method requires explicit conversion of the byte value. ```python >>> import bitmath >>> a_mebibyte = bitmath.MiB(1) >>> a_mebibyte_sized_kibibyte = bitmath.KiB(bytes=a_mebibyte.bytes) >>> a_mebibyte == a_mebibyte_sized_kibibyte True >>> print(a_mebibyte, a_mebibyte_sized_kibibyte) 1.0 MiB 1024.0 KiB ``` -------------------------------- ### Instance Methods Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md bitmath objects come with a few basic methods for conversion and formatting. ```APIDOC ## Instance Methods bitmath objects come with a few basic methods: `to_THING()`, `format()`, and [`best_prefix()`](#best_prefix). ### to_THING() Like the [available classes](classes.md#classes-available), there are 32 `to_THING()` methods available. `THING` is any of the bitmath classes. You can even `to_THING()` an instance into itself again: ```python >>> from bitmath import * >>> one_mib = MiB(1) >>> one_mib_in_kb = one_mib.to_kb() >>> one_mib == one_mib_in_kb True >>> another_mib = one_mib.to_MiB() >>> print(one_mib, one_mib_in_kb, another_mib) 1.0 MiB 8388.608 kb 1.0 MiB >>> six_TB = TB(6) >>> six_TB_in_bits = six_TB.to_Bit() >>> print(six_TB, six_TB_in_bits) 6.0 TB 4.8e+13 b >>> six_TB == six_TB_in_bits True ``` ### best_prefix() ``` -------------------------------- ### Accessing Instance Attributes - Singular Unit Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Gets the singular string representation of the instance's prefix unit. ```python >>> b = bitmath.Byte(1337) >>> print(b.unit_singular) B ``` -------------------------------- ### Basic Arithmetic with bitmath Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/index.md Demonstrates basic arithmetic operations like subtraction and division using bitmath objects. Ensure bitmath is imported before use. ```python import bitmath log_size = bitmath.kB(137.4) log_zipped_size = bitmath.Byte(987) print("Compression saved %s space" % (log_size - log_zipped_size)) ``` ```python thumb_drive = bitmath.GiB(12) song_size = bitmath.MiB(5) songs_per_drive = thumb_drive / song_size print(songs_per_drive) ``` -------------------------------- ### Accessing Instance Attributes - Unit Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Gets the string representation of the instance's prefix unit (e.g., 'MiB', 'kB'). ```python >>> b = bitmath.Byte(1337) >>> print(b.unit) B ``` -------------------------------- ### Convert Units with bitmath Source: https://github.com/timlnx/bitmath/blob/master/README.rst Convert a file size from one unit to another using the .to_() method. For example, convert GiB to MiB. ```python >>> from bitmath import * >>> dvd_size = GiB(4.7) >>> print("DVD Size in MiB: %s" % dvd_size.to_MiB()) DVD Size in MiB: 4812.8 MiB ``` -------------------------------- ### List Directory Contents with bitmath.listdir() Source: https://github.com/timlnx/bitmath/blob/master/README.rst Iterate through directory contents and display file sizes with their best prefix. Options include following symbolic links, relative paths, and determining the best prefix for display. ```python >>> for i in bitmath.listdir('./tests/', followlinks=True, relpath=True, bestprefix=True): ... print(i) ... ('tests/test_file_size.py', KiB(9.2900390625)) ('tests/test_basic_math.py', KiB(7.1767578125)) ('tests/__init__.py', KiB(1.974609375)) ('tests/test_bitwise_operations.py', KiB(2.6376953125)) ('tests/test_context_manager.py', KiB(3.7744140625)) ('tests/test_representation.py', KiB(5.2568359375)) ('tests/test_properties.py', KiB(2.03125)) ('tests/test_instantiating.py', KiB(3.4580078125)) ('tests/test_future_math.py', KiB(2.2001953125)) ('tests/test_best_prefix_BASE.py', KiB(2.1044921875)) ('tests/test_rich_comparison.py', KiB(3.9423828125)) ('tests/test_best_prefix_NIST.py', KiB(5.431640625)) ('tests/test_unique_testcase_names.sh', Byte(311.0)) ('tests/.coverage', KiB(3.1708984375)) ('tests/test_best_prefix_SI.py', KiB(5.34375)) ('tests/test_to_built_in_conversion.py', KiB(1.798828125)) ('tests/test_to_Type_conversion.py', KiB(8.0185546875)) ('tests/test_sorting.py', KiB(4.2197265625)) ('tests/listdir_symlinks/10_byte_file_link', Byte(10.0)) ('tests/listdir_symlinks/depth1/depth2/10_byte_file', Byte(10.0)) ('tests/listdir_nosymlinks/depth1/depth2/10_byte_file', Byte(10.0)) ('tests/listdir_nosymlinks/depth1/depth2/1024_byte_file', KiB(1.0)) ('tests/file_sizes/kbytes.test', KiB(1.0)) ('tests/file_sizes/bytes.test', Byte(38.0)) ('tests/listdir/10_byte_file', Byte(10.0)) ``` -------------------------------- ### Apply Custom Formatting with bitmath.format() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md Shows how to use the bitmath.format() context manager with a custom format string to display bitmath instances in scientific notation. It also demonstrates that formatting reverts to default after exiting the context. ```python import bitmath print("Some instances: %s, %s" % (bitmath.KiB(1 / 3.0), bitmath.Bit(512))) with bitmath.format("{value:e}-{unit}"): print("Some instances: %s, %s" % (bitmath.KiB(1 / 3.0), bitmath.Bit(512))) print("Some instances: %s, %s" % (bitmath.KiB(1 / 3.0), bitmath.Bit(512))) ``` -------------------------------- ### Accessing Instance Attributes - Binary Representation Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Shows how to get the binary representation of an instance's value in bits using the 'binary' attribute. ```python >>> b = bitmath.Byte(1337) >>> print(b.binary) 0b10100111001000 ``` -------------------------------- ### Convert Bytes to MB Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Demonstrates creating a Byte object and retrieving its MB equivalent. ```python >>> bitmath.Byte((10**6)*2048).MB MB(2048.0) ``` -------------------------------- ### bitmath.listdir() Source: https://github.com/timlnx/bitmath/blob/master/README.rst Lists the contents of a directory, returning file paths and their sizes as bitmath objects. ```APIDOC ## bitmath.listdir() ### Description Lists the contents of a directory, returning file paths and their sizes as bitmath objects. Supports options for following symbolic links, relative paths, and best prefix representation. ### Method ```python bitmath.listdir(path: str, followlinks: bool = False, relpath: bool = False, bestprefix: bool = False) ``` ### Parameters #### Path Parameters - **path** (str) - Required - The directory path to list. - **followlinks** (bool) - Optional - Whether to follow symbolic links. Defaults to False. - **relpath** (bool) - Optional - Whether to return relative paths. Defaults to False. - **bestprefix** (bool) - Optional - Whether to represent sizes using the best prefix. Defaults to False. ### Request Example ```python >>> for i in bitmath.listdir('./tests/', followlinks=True, relpath=True, bestprefix=True): ... print(i) ... ('tests/test_file_size.py', KiB(9.2900390625)) ('tests/test_basic_math.py', KiB(7.1767578125)) ('tests/__init__.py', KiB(1.974609375)) ('tests/test_bitwise_operations.py', KiB(2.6376953125)) ('tests/test_context_manager.py', KiB(3.7744140625)) ('tests/test_representation.py', KiB(5.2568359375)) ('tests/test_properties.py', KiB(2.03125)) ('tests/test_instantiating.py', KiB(3.4580078125)) ('tests/test_future_math.py', KiB(2.2001953125)) ('tests/test_best_prefix_BASE.py', KiB(2.1044921875)) ('tests/test_rich_comparison.py', KiB(3.9423828125)) ('tests/test_best_prefix_NIST.py', KiB(5.431640625)) ('tests/test_unique_testcase_names.sh', Byte(311.0)) ('tests/.coverage', KiB(3.1708984375)) ('tests/test_best_prefix_SI.py', KiB(5.34375)) ('tests/test_to_built_in_conversion.py', KiB(1.798828125)) ('tests/test_to_Type_conversion.py', KiB(8.0185546875)) ('tests/test_sorting.py', KiB(4.2197265625)) ('tests/listdir_symlinks/10_byte_file_link', Byte(10.0)) ('tests/listdir_symlinks/depth1/depth2/10_byte_file', Byte(10.0)) ('tests/listdir_nosymlinks/depth1/depth2/10_byte_file', Byte(10.0)) ('tests/listdir_nosymlinks/depth1/depth2/1024_byte_file', KiB(1.0)) ('tests/file_sizes/kbytes.test', KiB(1.0)) ('tests/file_sizes/bytes.test', Byte(38.0)) ('tests/listdir/10_byte_file', Byte(10.0)) ``` ``` -------------------------------- ### Custom Progressbar2 Widget for Data Transfer Speed Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/integration_examples.md Create a custom progressbar2 widget to display data transfer speed in human-readable bitmath units. Install progressbar2 before use. ```bash pip install progressbar2 ``` ```python import time import progressbar import bitmath class DataTransferSpeed(progressbar.widgets.FormatWidgetMixin, progressbar.widgets.TimeSensitiveMixin): """Display transfer speed as a human-readable bitmath value per second.""" def __call__(self, progress, data, **kwargs): elapsed = data.get("seconds_elapsed") or 0 if elapsed <= 0 or data.get("value") is None: return "?? B/s" bytes_done = data["value"] speed = bitmath.Byte(bytes_done / elapsed).best_prefix() return f"{speed:.2f}/s" def simulate_download(total_bytes): widgets = [ "Downloading: ", progressbar.Bar(), " ", progressbar.Percentage(), " ", DataTransferSpeed(), " ", progressbar.ETA(), ] with progressbar.ProgressBar( max_value=total_bytes, widgets=widgets ) as bar: received = 0 chunk = total_bytes // 50 while received < total_bytes: time.sleep(0.05) received = min(received + chunk, total_bytes) bar.update(received) if __name__ == "__main__": # Simulate a 100 MiB download simulate_download(int(bitmath.MiB(100).to_Byte())) ``` -------------------------------- ### Custom Click Parameter Type for Bitmath Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/integration_examples.md Implement a custom click parameter type to parse bitmath unit strings directly in command-line arguments. Ensure bitmath is installed before use. ```bash pip install click ``` ```python import click import bitmath class BitmathParamType(click.ParamType): """A click parameter type that accepts bitmath unit strings.""" name = "SIZE" def convert(self, value, param, ctx): if isinstance(value, bitmath.Bitmath): return value try: return bitmath.parse_string(value) except ValueError: self.fail( f"{value!r} is not a recognized bitmath unit string " "(examples: 10MiB, 1.5GiB, 500kB)", param, ctx, ) BITMATH = BitmathParamType() @click.command() @click.option( "--block-size", type=BITMATH, required=True, help="Block size with unit, e.g. 10MiB", ) def main(block_size): """Example command using a bitmath click parameter type.""" click.echo(f"Block size: {block_size}") click.echo(f"In KiB: {block_size.to_KiB():.2f}") if __name__ == "__main__": main() ``` -------------------------------- ### Print Human-Readable File Sizes in Python Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/real_life_examples.md Use bitmath to convert file sizes obtained from os.path.getsize() into KiB for display. Requires importing os and bitmath. ```python import os from bitmath import * these_files = os.listdir('.') for f in these_files: f_size = Byte(os.path.getsize(f)) print("%s - %s" % (f, f_size.to_KiB())) ``` -------------------------------- ### bitmath.listdir() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/index.md Lists the contents of a directory with their sizes. ```APIDOC ## bitmath.listdir() ### Description Lists the contents of a directory, returning tuples of relative path and size. ### Method `bitmath.listdir(path, followlinks=False, relpath=False, bestprefix=False)` ### Parameters #### Path Parameters - **path** (str) - Required - The directory path to list. - **followlinks** (bool) - Optional - Whether to follow symbolic links. Defaults to `False`. - **relpath** (bool) - Optional - Whether to return relative paths. Defaults to `False`. - **bestprefix** (bool) - Optional - Whether to format sizes using the best human-readable prefix. Defaults to `False`. ### Request Example ```python >>> import bitmath >>> for i in bitmath.listdir('./tests/', followlinks=True, relpath=True, bestprefix=True): ... print(i) ... ('tests/test_file_size.py', KiB(9.2900390625)) ('tests/test_basic_math.py', KiB(7.1767578125)) ('tests/__init__.py', KiB(1.974609375)) ... ``` ``` -------------------------------- ### Custom formatting with instance.format() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Use `instance.format()` for full control over the output string, allowing access to all instance attributes like `{value}`, `{unit}`, `{bits}`, and `{bytes}`. This is useful when you need to weave specific attributes into the output. ```python >>> size = bitmath.MiB(1 / 3.0) >>> size.format("{value:.2f} {unit} ({bits:.0f} bits)") '0.33 MiB (2796202 bits)' ``` -------------------------------- ### Initialize bitmath instance using from_other() class method Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/classes.md Utilizes the `from_other()` class method for a more direct way to initialize a bitmath instance based on another instance's value. This method handles the conversion internally. ```python >>> a_mebibyte = bitmath.MiB(1) >>> a_big_kibibyte = bitmath.KiB.from_other(a_mebibyte) >>> a_mebibyte == a_big_kibibyte True >>> print(a_mebibyte, a_big_kibibyte) 1.0 MiB 1024.0 KiB ``` -------------------------------- ### Get File Size with bitmath Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md Use bitmath.getsize() to obtain a bitmath instance representing the size of a file. It supports NIST or SI units and can return raw bytes if bestprefix is False. pathlib.Path objects are accepted. ```python import os stat = os.stat('./bitmath/__init__.py') stat.st_size # raw bytes — no unit context 34159 f"{stat.st_size / 1024:.4f} KiB" # manual math, locked to one unit '33.3584 KiB' ``` ```python import bitmath, pathlib # NIST default - picks the most human-readable prefix automatically print(bitmath.getsize('./bitmath/__init__.py')) 33.3583984375 KiB # pathlib.Path works directly, no conversion needed print(bitmath.getsize(pathlib.Path('./bitmath/__init__.py'))) 33.3583984375 KiB # SI units instead of NIST print(bitmath.getsize('./bitmath/__init__.py', system=bitmath.SI)) 34.159 kB # skip prefix selection — get the value as a plain Byte instance print(bitmath.getsize('./bitmath/__init__.py', bestprefix=False)) 34159.0 B ``` -------------------------------- ### Multiply bitmath instances (byte-level math) Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/appendices/mixed_math.rst When multiplying two bitmath instances, the math is performed at the byte-level, ignoring prefix units. The result is in the unit of the LHS. For byte units, the result is technically squared. Use .best_prefix() to get a more intuitive value. ```python >>> bitmath.kB(3).bytes, bitmath.MiB(5).bytes (3000.0, 5242880.0) >>> bitmath.best_prefix(3000 * 5242880) GiB(14.6484375) ``` ```python >>> bitmath.Byte(3000) * bitmath.MiB(5) B(15728640000.0) ``` ```python >>> (bitmath.Byte(3000) * bitmath.MiB(5)).best_prefix() GiB(14.6484375) ``` -------------------------------- ### Default Bitmath Instance String Representation Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Demonstrates the default string representation of a bitmath instance, which is often verbose. This serves as a baseline for understanding the need for custom formatting. ```python >>> leet_bits = Bit(1337) >>> print(leet_bits) 1337.0 b ``` -------------------------------- ### Summing bitmath objects with built-in sum() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Use Python's built-in sum() function with bitmath objects. The result type matches the first element in the iterable. Accumulation starts correctly due to the identity element `0 + bm` returning `bm`. ```python >>> import bitmath >>> sum([bitmath.KiB(1), bitmath.KiB(2)]) KiB(3.0) ``` ```python >>> sum([bitmath.Byte(1), bitmath.MiB(1), bitmath.GiB(1)]) Byte(1074790401.0) ``` -------------------------------- ### Basic Arithmetic Operations in bitmath Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Demonstrates basic arithmetic operations like addition and multiplication. Ensure operands are compatible bitmath instances or numbers. ```python >>> eighty_four_mib = fourty_two_mib + fourty_two_mib_in_kib >>> eighty_four_mib MiB(84.0) >>> eighty_four_mib == fourty_two_mib * 2 True ``` -------------------------------- ### Format Specification Mini-Language Example Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Demonstrates the structure of a format specifier like {value:.2f} used in Python's string formatting. The 'f' indicates float formatting, '2' sets precision to two digits, '.' precedes precision for floats, ':' separates the attribute from the specifier, and 'value' is the attribute name. ```default {value:.2f} | ||| | | |\---- The "f" says to format this as a floating point type | | |\----- The 2 indicates we want 2 digits of precision (default is 6) | | \------ The "." character must precede the precision specifier for floats | \------- The : separates the attribute name from the formatting specification \---------- The name of the attribute to print ``` -------------------------------- ### Query Device Capacity with bitmath.query_device_capacity() Source: https://github.com/timlnx/bitmath/blob/master/README.rst Query the capacity of a storage device by passing a file-like object. The best_prefix() method is used to display the capacity in the most appropriate unit. ```python >>> import bitmath >>> with open('/dev/sda') as fp: ... root_disk = bitmath.query_device_capacity(fp) ... print(root_disk.best_prefix()) ... 238.474937439 GiB ``` -------------------------------- ### Same-unit addition with bitmath instances Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/appendices.md Demonstrates adding two bitmath instances of the same unit. This operation preserves the unit and returns a new bitmath instance. ```python >>> Byte(1) + Byte(1) Byte(2.0) ``` -------------------------------- ### Sort File Sizes (Ascending) Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Illustrates sorting a list of bitmath objects representing file sizes in ascending order. ```python >>> from bitmath import * >>> import os >>> sizes = [] >>> for f in os.listdir('./tests/'): ... sizes.append(KiB(os.path.getsize('./tests/' + f))) >>> print(sizes) [KiB(7337.0), KiB(1441.0), KiB(2126.0), KiB(2178.0), KiB(2326.0), KiB(4003.0), KiB(48.0), KiB(1770.0), KiB(7892.0), KiB(4190.0)] >>> print(sorted(sizes)) [KiB(48.0), KiB(1441.0), KiB(1770.0), KiB(2126.0), KiB(2178.0), KiB(2326.0), KiB(4003.0), KiB(4190.0), KiB(7337.0), KiB(7892.0)] >>> human_sizes = [s.best_prefix() for s in sizes] >>> print(sorted(human_sizes)) [KiB(48.0), MiB(1.4072265625), MiB(1.728515625), MiB(2.076171875), MiB(2.126953125), MiB(2.271484375), MiB(3.9091796875), MiB(4.091796875), MiB(7.1650390625), MiB(7.70703125)] ``` -------------------------------- ### best_prefix() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Returns an equivalent instance using the best human-readable prefix-unit to represent it. This is useful for presenting data in a more understandable format, similar to how a bank statement would show dollars instead of pennies. ```APIDOC ## best_prefix() ### Description Return an equivalent instance which uses the best human-readable prefix-unit to represent it. ### Parameters * **system** (*int*) – one of [`bitmath.NIST`](module.md#bitmath.NIST) or [`bitmath.SI`](module.md#bitmath.SI) ### Returns An equivalent [`bitmath`](module.md#module-bitmath) instance ### Return type [`bitmath`](module.md#module-bitmath) ### Raises **ValueError** – if an invalid unit system is given for `system` ``` -------------------------------- ### bitmath.listdir() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md Recurses a directory tree, yielding paths and bitmath instances for discovered files. Supports filtering, relative paths, and unit system preferences. ```APIDOC ## bitmath.listdir(search_base, followlinks=False, glob='*', relpath=False, bestprefix=False, system=bitmath.NIST) ### Description This is a generator which recurses a directory tree yielding 2-tuples of: The absolute/relative path to a discovered file and a bitmath instance representing the *apparent size* of the file. ### Parameters #### Path Parameters - **search_base** (str or pathlib.Path) - Required - The directory to begin walking down. May be a plain string or a `pathlib.Path` object. - **followlinks** (bool) - Optional - Default: `False`. Whether or not to follow symbolic links to directories. - **glob** (string) - Optional - Default: `*`. A glob to filter results with. - **relpath** (bool) - Optional - Default: `False`. Returns the fully qualified path to each discovered file. `True` to return the relative path from the present working directory to the discovered file. - **bestprefix** (bool) - Optional - Default: `False`. Returns [`Byte`](classes.md#bitmath.Byte) instances. Set to `True` to return the best human-readable prefix unit for representation. - **system** (One of [`bitmath.NIST`](#bitmath.NIST) or [`bitmath.SI`](#bitmath.SI)) - Optional - Default: [`bitmath.NIST`](#bitmath.NIST). Set a prefix preferred unit system. Requires `bestprefix` is `True`. #### NOTE Symlinks to **files** are followed automatically. ``` -------------------------------- ### Query Volume Capacity with SI Prefixes Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md Opt into SI (decimal) prefixes for human-readable output by specifying the system parameter. ```python >>> cap = bitmath.query_capacity("/", system=bitmath.SI) >>> print(cap.total) 500.068 GB ``` -------------------------------- ### Query Device Capacity with bitmath.query_device_capacity() Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/index.md Use `bitmath.query_device_capacity()` to determine the total capacity of a storage device. It requires a file-like object representing the device. ```python >>> import bitmath >>> with open('/dev/sda') as fp: ... root_disk = bitmath.query_device_capacity(fp) ... print(root_disk.best_prefix()) ... 238.474937439 GiB ``` -------------------------------- ### Comparing NIST and SI Prefixes Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/appendices/on_units.rst Demonstrates the approximate equivalence of NIST (base-2) and SI (base-10) prefixes for small values and their divergence for larger values. Use this to understand the practical differences in unit representation. ```python In [15]: one_kilo = 1 * 10**3 In [16]: one_kibi = 1 * 2**10 In [17]: round(one_kilo / one_kibi, 2) Out[17]: 0.98 In [18]: one_tera = 1 * 10**12 In [19]: one_tebi = 1 * 2**40 In [20]: round(one_tera / one_tebi, 2) Out[20]: 0.91 In [21]: one_exa = 1 * 10**18 In [22]: one_exbi = 1 * 2**60 In [23]: round(one_exa / one_exbi, 2) Out[23]: 0.87 ``` -------------------------------- ### Query Raw Physical Device Capacity (Windows) Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/module.md Query the raw physical capacity of block devices on Windows. Requires administrator privileges. Returns a bitmath.Byte instance. ```python >>> import bitmath >>> drives = [r'\\.\\PhysicalDrive0', r'\\.\\PhysicalDrive1'] >>> for path in drives: ... with open(path, 'rb') as drive: ... size = bitmath.query_device_capacity(drive).best_prefix() ... print(f"Drive {path}: {size}") Drive \\.\\PhysicalDrive0: 80.0 GiB Drive \\.\\PhysicalDrive1: 14.311 TiB ``` -------------------------------- ### Sort File Sizes (Descending) Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/simple_examples.md Demonstrates sorting a list of bitmath objects representing file sizes in descending order using `reverse=True`. ```python >>> print(sorted(human_sizes, reverse=True)) [MiB(7.70703125), MiB(7.1650390625), MiB(4.091796875), MiB(3.9091796875), MiB(2.271484375), MiB(2.126953125), MiB(2.076171875), MiB(1.728515625), MiB(1.4072265625), KiB(48.0)] ``` -------------------------------- ### Instance Method: to_THING() for Unit Conversion Source: https://github.com/timlnx/bitmath/blob/master/docsite/source/instances.md Converts an instance to another bitmath unit type using the to_THING() method. Demonstrates conversion to different units and back to the same unit. ```python >>> from bitmath import * >>> one_mib = MiB(1) >>> one_mib_in_kb = one_mib.to_kb() >>> one_mib == one_mib_in_kb True >>> another_mib = one_mib.to_MiB() >>> print(one_mib, one_mib_in_kb, another_mib) 1.0 MiB 8388.608 kb 1.0 MiB >>> six_TB = TB(6) >>> six_TB_in_bits = six_TB.to_Bit() >>> print(six_TB, six_TB_in_bits) 6.0 TB 4.8e+13 b >>> six_TB == six_TB_in_bits True ```