Code Monkey home page Code Monkey logo

bitmath's Introduction

image

image

image

bitmath

bitmath simplifies many facets of interacting with file sizes in various units. Originally focusing on file size unit conversion, functionality now includes:

  • Converting between SI and NIST prefix units (kB to GiB)
  • Converting between units of the same type (SI to SI, or NIST to NIST)
  • Automatic human-readable prefix selection (like in hurry.filesize)
  • Basic arithmetic operations (subtracting 42KiB from 50GiB)
  • Rich comparison operations (1024 Bytes == 1KiB)
  • bitwise operations (<<, >>, &, |, ^)
  • Reading a device's storage capacity (Linux/OS X support only)
  • argparse integration as a custom type
  • click integration as a custom parameter type
  • progressbar integration as a better file transfer speed widget
  • String parsing
  • Sorting

In addition to the conversion and math operations, bitmath provides human readable representations of values which are suitable for use in interactive shells as well as larger scripts and applications. The format produced for these representations is customizable via the functionality included in stdlibs string.format.

In discussion we will refer to the NIST units primarily. I.e., instead of "megabyte" we will refer to "mebibyte". The former is 10^3 = 1,000,000 bytes, whereas the second is 2^20 = 1,048,576 bytes. When you see file sizes or transfer rates in your web browser, most of the time what you're really seeing are the base-2 sizes/rates.

Don't Forget! The source for bitmath is available on GitHub.

And did we mention there's almost 200 unittests? Check them out for yourself.

Running the tests should be as simple as calling the ci-all target in the Makefile: make ci-all. Please file a bug report if you run into issues.

Installation

The easiest way to install bitmath is via dnf (or yum) if you're on a Fedora/RHEL based distribution. bitmath is available in the main Fedora repositories, as well as the EPEL6 and EPEL7 repositories. There are now dual python2.x and python3.x releases available.

Python 2.x:

$ sudo dnf install python2-bitmath

Python 3.x:

$ sudo dnf install python3-bitmath

Note

Upgrading: If you have the old python-bitmath package installed presently, you could also run sudo dnf update python-bitmath instead

PyPi:

You could also install bitmath from PyPi if you like:

$ sudo pip install bitmath

Note

pip installs need pip >= 1.1. To workaround this, download bitmath, from PyPi and then pip install bitmath-x.y.z.tar.gz. See issue #57 for more information.

PPA:

Ubuntu Xenial, Wily, Vivid, Trusty, and Precise users can install bitmath from the launchpad PPA:

$ sudo add-apt-repository ppa:tbielawa/bitmath
$ sudo apt-get update
$ sudo apt-get install python-bitmath

Source:

Or, if you want to install from source:

$ sudo python ./setup.py install

If you want the bitmath manpage installed as well:

$ sudo make install

Documentation

The main documentation lives at http://bitmath.readthedocs.org/en/latest/.

Topics include:

  • The bitmath Module
    • Utility Functions
    • Context Managers
    • Module Variables
    • argparse integration
    • click integration
    • progressbar integration
  • The bitmath command-line Tool
  • Classes
    • Initializing
    • Available Classes
    • Class Methods
  • Instances
    • Instance Attributes
    • Instance Methods
    • Instance Properties
    • The Formatting Mini-Language
  • Getting Started
    • Tables of Supported Operations
    • Basic Math
    • Unit Conversion
    • Rich Comparison
    • Sorting
  • Real Life Examples
    • Download Speeds
    • Calculating how many files fit on a device
    • Printing Human-Readable File Sizes in Python
    • Calculating Linux BDP and TCP Window Scaling
  • Contributing to bitmath
  • Appendices
    • Rules for Math
    • On Units
    • Who uses Bitmath
    • Related Projects
  • NEWS
  • Copyright

Examples

Arithmetic

>>> import bitmath
>>> log_size = bitmath.kB(137.4)
>>> log_zipped_size = bitmath.Byte(987)
>>> print "Compression saved %s space" % (log_size - log_zipped_size)
Compression saved 136.413kB space
>>> thumb_drive = bitmath.GiB(12)
>>> song_size = bitmath.MiB(5)
>>> songs_per_drive = thumb_drive / song_size
>>> print songs_per_drive
2457.6

Convert Units

File size unit conversion:

>>> 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

Select a human-readable unit

>>> small_number = kB(100)
>>> ugly_number = small_number.to_TiB()

>>> print ugly_number
9.09494701773e-08 TiB
>>> print ugly_number.best_prefix()
97.65625 KiB

Rich Comparison

>>> cd_size = MiB(700)
>>> cd_size > dvd_size
False
>>> cd_size < dvd_size
True
>>> MiB(1) == KiB(1024)
True
>>> MiB(1) <= KiB(1024)
True

Sorting

>>> 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)]

Custom Formatting

  • Use of the custom formatting system
  • All of the available instance properties

Example:

>>> 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)
Formatting attributes for 5.96046447754 MiB
This instances prefix unit is MiB, which is a NIST type unit
The unit value is 5.96046447754
This value can be truncated to just 1 digit of precision: 6.0
In binary this looks like: 0b10111110101111000010000000
The prefix unit is derived from a base of 2
Which is raised to the power 20
There are 6250000.0 bytes in this instance
The instance is 50000000.0 bits large
bytes/bits without trailing decimals: 6250000/50000000

Utility Functions

bitmath.getsize()

>>> print bitmath.getsize('python-bitmath.spec')
3.7060546875 KiB

bitmath.parse_string()

Parse a string with standard units:

>>> import bitmath
>>> a_dvd = bitmath.parse_string("4.7 GiB")
>>> print type(a_dvd)
<class 'bitmath.GiB'>
>>> print a_dvd
4.7 GiB

bitmath.parse_string_unsafe()

Parse a string with ambiguous units:

>>> import bitmath
>>> a_gig = bitmath.parse_string_unsafe("1gb")
>>> print type(a_gig)
<class 'bitmath.GB'>
>>> a_gig == bitmath.GB(1)
True
>>> bitmath.parse_string_unsafe('1gb') == bitmath.parse_string_unsafe('1g')
True

bitmath.query_device_capacity()

>>> import bitmath
>>> with open('/dev/sda') as fp:
...     root_disk = bitmath.query_device_capacity(fp)
...     print root_disk.best_prefix()
...
238.474937439 GiB

bitmath.listdir()

>>> 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))

Formatting

>>> with bitmath.format(fmt_str="[{value:.3f}@{unit}]"):
...     for i in bitmath.listdir('./tests/', followlinks=True, relpath=True, bestprefix=True):
...         print i[1]
...
[9.290@KiB]
[7.177@KiB]
[1.975@KiB]
[2.638@KiB]
[3.774@KiB]
[5.257@KiB]
[2.031@KiB]
[3.458@KiB]
[2.200@KiB]
[2.104@KiB]
[3.942@KiB]
[5.432@KiB]
[311.000@Byte]
[3.171@KiB]
[5.344@KiB]
[1.799@KiB]
[8.019@KiB]
[4.220@KiB]
[10.000@Byte]
[10.000@Byte]
[10.000@Byte]
[1.000@KiB]
[1.000@KiB]
[38.000@Byte]
[10.000@Byte]

argparse Integration

Example script using bitmath.integrations.bmargparse.BitmathType as an argparser argument type:

import argparse
from bitmath.integrations.bmargparse import BitmathType
parser = argparse.ArgumentParser(
    description="Arg parser with a bitmath type argument")
parser.add_argument('--block-size',
                    type=BitmathType,
                    required=True)

results = parser.parse_args()
print "Parsed in: {PARSED}; Which looks like {TOKIB} as a Kibibit".format(
    PARSED=results.block_size,
    TOKIB=results.block_size.Kib)

If ran as a script the results would be similar to this:

$ python ./bmargparse.py --block-size 100MiB
Parsed in: 100.0 MiB; Which looks like 819200.0 Kib as a Kibibit

click Integration

Example script using bitmath.integrations.bmclick.BitmathType as an click parameter type:

import click
from bitmath.integrations.bmclick import BitmathType

@click.command()
@click.argument('size', type=BitmathType())
def best_prefix(size):
   click.echo(size.best_prefix())

If ran as a script the results should be similar to this:

$ python ./bestprefix.py "1024 KiB"
1.0 MiB

progressbar Integration

Use bitmath.integrations.bmprogressbar.BitmathFileTransferSpeed as a progressbar file transfer speed widget to monitor download speeds:

import requests
import progressbar
import bitmath
from bitmath.integrations.bmprogressbar import BitmathFileTransferSpeed

FETCH = 'https://www.kernel.org/pub/linux/kernel/v3.0/patch-3.16.gz'
widgets = ['Bitmath Progress Bar Demo: ', ' ',
           progressbar.Bar(marker=progressbar.RotatingMarker()), ' ',
           BitmathFileTransferSpeed()]

r = requests.get(FETCH, stream=True)
size = bitmath.Byte(int(r.headers['Content-Length']))
pbar = progressbar.ProgressBar(widgets=widgets, maxval=int(size),
                               term_width=80).start()
chunk_size = 2048
with open('/dev/null', 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)
        if (pbar.currval + chunk_size) < pbar.maxval:
            pbar.update(pbar.currval + chunk_size)
pbar.finish()

If ran as a script the results would be similar to this:

$ python ./smalldl.py
Bitmath Progress Bar Demo:  ||||||||||||||||||||||||||||||||||||||||| 1.58 MiB/s

bitmath's People

Contributors

alkuzad avatar ashcrow avatar blochberger avatar davidfischer-ch avatar drewbrew avatar encukou avatar hikusukih avatar kapsh avatar mkaz avatar ssut avatar tbielawa avatar tonycpsu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

bitmath's Issues

Set up a ReadTheDocs site

So the README is getting pretty long now. I think it's time to convert the docs into a proper site.

This will require converting all the Markdown to RST, but we can get over that.

CLI script inconsistent output when with '--to' option

$ bitmath -t kb 1337
10.696

$ bitmath 1337
1.3056640625 KiB

The first example does not include the unit in the output. This is not desired.

In the second example the prefix unit is printed, this is the expected result.

__truediv__ is broken for num / bm

======================================================================
ERROR: truediv: number / bitmath = number
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tbielawa/Projects/bitmath/tests/test_future_math.py", line 61, in test_number_div_bitmath_is_number
    result = num1 / bm1
TypeError: unsupported operand type(s) for /: 'int' and 'KiB'

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (errors=1)

However, bm / bm and bm / num work properly.

Installing in Python 2.6.5 yields: No such file or directory: 'README.rst'

I was testing an application using Ubuntu 10.04 running on docker which couldn't install bitmath.

# pip install bitmath
Downloading/unpacking bitmath
  Running setup.py egg_info for package bitmath
    Traceback (most recent call last):
      File "<string>", line 13, in <module>
      File "/app/build/bitmath/setup.py", line 34, in <module>
        pypi_notice = open('README.rst', 'r').read()
    IOError: [Errno 2] No such file or directory: 'README.rst'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 13, in <module>

  File "/app/build/bitmath/setup.py", line 34, in <module>

    pypi_notice = open('README.rst', 'r').read()

IOError: [Errno 2] No such file or directory: 'README.rst'

----------------------------------------
Command python setup.py egg_info failed with error code 1

System info

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 10.04 LTS
Release:        10.04
Codename:       lucid

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2

Reproduce:

docker run -it --rm ubuntu:10.04 /bin/bash

$ sudo apt-get install python-pip
$ sudo pip install bitmath

Verify that sorting a list of bitmath items works

This seems wrong to me:

>>> items = [GiB(0.75), GiB(1.25), KiB(1024), GiB(1)]
>>> items
[GiB(0.75), GiB(1.25), KiB(1024.0), GiB(1.0)]
>>> sorted(items)
[KiB(1024.0), GiB(0.75), GiB(1.0), GiB(1.25)]
>>> KiB(0.75).to_KiB()
KiB(0.75)


>>> items = [GiB(0.75), MiB(765), GiB(1.25), KiB(1024), GiB(1)]
>>> sorted(items)
[KiB(1024.0), MiB(765.0), GiB(0.75), GiB(1.0), GiB(1.25)]

Might be right though. Need to check.

Either way though. Need to write some unittests to verify sorting works.

RFE: Integration with argparse: parse_string an option

Ex, an image converting program might want to have an option to reduce image quality until a certain threshold is met. Maybe, to reduce all images in quality until the size of each is <= 1MiB

img-convert.py --reduce --max-size 1MiB images/*.jpg

Might just be a good example to have.

Updating "the index" has to be done in too many places

Places requiring updates if the "index" is changed

  • Github - via README.md
  • PyPi - via .pypi_notice
  • RTD - Via docsite/sources/index.rst

I think .pypi_notice and index.rst can become the same file. A quick check looks like they have all of the same contents.

add human readable conversion methods

I miss a module that could do conversion to human readable format BUT with automatic finding of most sane unit prefix.

So for example 1024B would get converted to 1kB. 1024M -> 1GB and so on. Same for other units.

to_humanB()
to_humanb()

maybe.

'make rpm' fails on RHEL 6

+ /usr/bin/python2 -m unittest discover
Traceback (most recent call last):
  File "/usr/lib64/python2.6/runpy.py", line 122, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib64/python2.6/runpy.py", line 34, in _run_code
    exec code in run_globals
  File "/usr/lib64/python2.6/unittest.py", line 874, in <module>
    main(module=None)
  File "/usr/lib64/python2.6/unittest.py", line 815, in __init__
    self.parseArgs(argv)
  File "/usr/lib64/python2.6/unittest.py", line 842, in parseArgs
    self.createTests()
  File "/usr/lib64/python2.6/unittest.py", line 848, in createTests
    self.module)
  File "/usr/lib64/python2.6/unittest.py", line 612, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/lib64/python2.6/unittest.py", line 575, in loadTestsFromName
    module = __import__('.'.join(parts_copy))
ImportError: No module named discover
error: Bad exit status from /var/tmp/rpm-tmp.jcsX4R (%check)


RPM build errors:
    Bad exit status from /var/tmp/rpm-tmp.jcsX4R (%check)
make: *** [rpm] Error 1

The unittests module doesn't support 'discover' in RHEL 6.

[root@ip-10-147-242-105 bitmath]# rpm -q python
python-2.6.6-37.el6_4.x86_64

Need to decide how to handle this.

RFE: instance representation is customizable

This came up in #6

Printing out instances can some times look a little messy:

In [12]: print "Git config is: %s" % Byte(os.path.getsize('/home/tbielawa/.gitconfig')).best_prefix()
Git config is: 1.380859375KiB

That would look a lot more readable if it printed the instance with less precision, say for example: 1.38KiB.

Need some kind of way(s) to allow for custom representation

best_prefix for negative values

The result of best_practive is always in Bits for negative values. It might be interesting to work on the absolute values, to get a more human readable result. Thanks for your work.

Fix travis-ci build

Travis and my local machine are disagreeing about sort order for the file size related tests.

Fix the build. Make the tests pass locally AND on travis.

Push out a 1.0.6 release

Ship what we have now. 1.0.7 will be the cleanup of this release.

After that, get your shit together and start producing tested and documented code when you write it. Not afterwards.

listdir should take directories into account

Directories are like files.... kinda...

listdir should return tuples for those too.

Questions:

  • Return the size of the symbolic link to a directory

or

  • Return the size of the dereferenced link

?

Getting odd error on Windows

'''Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

from bitmath import *
Traceback (most recent call last):
File "", line 1, in
File "build\bdist.win32\egg\bitmath__init__.py", line 67, in
ImportError: No module named fcntl'''

Docs update

Document:

  • New properties
  • "Best prefix" method
  • Instance formatting

RFE: Utility function/method for percentage of two bitmath types

As a user of the bitmath library, I want a way to calculate percentages of bitmath objects when designing progress-bar type widgets/displays, so that there is a standard way to do this without requiring me to write more code.


Imagine if you will, a progress bar:

Downloading [===========/        ] 100 MiB/120 MiB 83%

Calculating that can be kind of lame. What if there was a way with bitmath to calculate that percentage?

I'm imagining something like:

>>> import bitmath
>>> downloaded = bitmath.MiB(100)
>>> total = bitmath.MiB(120)
>>> downloaded.percent_of(total)
83.33

The above example is just my first idea. This could be done in any number of other ways (possibly more intelligently, too).


Maybe not in the MVP (minimum viable product), but a feature to keep in mind for the future would be finding a way to integrate with Python Progress Bar

https://pypi.python.org/pypi/progressbar/2.2

RFE: read capacity of a block device

Would be cool to be able to read the capacity of a block device. As if you could run getsize on /dev/sda or something.

How should this integrate with listdir?

  • Currently when you run listdir on /dev/ you get Byte(0.0) for devices. That's for any device -- TTYs, input devices, special block devices, and any other pseudo-device you can imagine
  • Reading block device capacity requires "raw" access to the device, this requires super user privs
  • If necessary privs aren't granted for the effective UID, should some kind of IO exception get raised, or should the device get skipped over?

etc etc

Cleanup links

Just discovered the sphinx-build commands make linkcheck target.

Criteria

  • Fix broken links
  • Cleanup redirects

Comparison issues with LARGE units

I began testing out adding support for the ZiB, YiB, Zib, and Yib units while working on #53. This broke the (new) unit tests immediately and in a non-obvious way. For example, when parsing 654 Zo:

======================================================================
FAIL: parse_string works on zettaoctet strings
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tbielawa/Projects/bitmath/tests/test_parse.py", line 87, in test_parse_Zo
    compare_to)
AssertionError: ZB(654.0) != ZB(654.0)

Interesting I think that the error message says two equal things are not equal, ZB(654.0) != ZB(654.0).

I did some initial debugging and figured out how the comparison is failing. It appears that the instances bytes parameters are of different types!

  • Parsed input bytes: 6.54e+23
  • Comparson bytes: 654000000000000000000000

Throw this into python real quck:

In [1]: n1 = 6.54e+23

In [2]: n2 = 654000000000000000000000

In [3]: print type(n1), type(n2)
<type 'float'> <type 'long'>

In [4]: n1 == n2
Out[4]: False

In [5]: n1 - n2
Out[5]: 0.0

BUT, you can work around this issue by explicitly instantiating the 'to parse' and the 'comparison' instances as floating point numbers

In [1]: import bitmath

In [2]: parsed = bitmath.parse_string("654.0 Zo")

In [4]: compare_to = bitmath.ZB(654.0)

In [5]: parsed == compare_to
Out[5]: True

In [8]: print parsed.bytes, compare_to.bytes
6.54e+23 6.54e+23

In [9]: print type(parsed.bytes), type(compare_to.bytes)
<type 'float'> <type 'float'>

For now I'm going to remove the code I added for the new unit support and then revisit this after finishing up the work in #53

Create deb packages and PPAs

It would be nice to provide bitmath builds in deb package format for users on Debian/Ubuntu systems. Creating PPA (personal package archives) to host the debs would be required as well.

This is in response to #57

Problems in parse_string

Bug 1 :

bitmath.parse_string('7.5KB')
ValueError: The unit KB is not a valid bitmath unit

Bug 2:
Please add a fix to parse strings with only SI units. e.g. 10K, 10M etc.

example:
bitmath.parse_string("4.7MB")
MB(4.7)

bitmath.parse_string("4.7M")
ValueError: The unit M is not a valid bitmath unit

RFE: bitmath.size(path)

As a bitmath user I want to give a/many file path(s) to a function and have it return appropriately sized unit instance(s) representing the size of the file(s)

Using "Real Life Example: Printing Human-Readable File Sizes in Python" from the README as reference:

>>> these_files = os.listdir('.')

>>> for f in these_files:
        f_size = Byte(os.path.getsize(f))
        print "%s - %s" % (f, f_size.to_KiB())

test_basic_math.py - 3.048828125KiB
__init__.py - 0.1181640625KiB
test_representation.py - 0.744140625KiB
test_to_Type_conversion.py - 2.2119140625KiB

Those outputs aren't very nice to look at. We could call the best_prefix method in our code ourselves, but why as the library user should that be our responsibility?

I'd like to see something handling these use cases:

  • bitmath.listdir(path, recurse=False, prefix=None) - an iterator yielding successive instances of appropriately sized bitmath objects for each item in path. Set prefix to a bitmath class (like bitmath.KiB) and all results will be in that unit instead. Set recurse to True and the given path will be walked, yielding instances for all sub directories.
  • bitmath.getsize(path, prefix=None) - Function that returns an appropriately sized bitmath object representing the item path. The prefix kwarg works like described for listdir.

module level tools, runnable from a CLI?

For reference, the json library has json.tool to handle input streams. You can run it on a shell prompt to pretty print json

curl http://something.json | python -m json.tool

Wondering if there's anything useful bitmath could do like this?

$ python -m bitmath.best 1024
KiB(1)

^ this would actually simplify my own personal frequent use case where I get a number in bytes printed in one shell,and I can't quite tell how big it is. Usually I'll just open another shell, import bitmath and then print out Byte(some_number).best_prefix().

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.