File: randfile.py

package info (click to toggle)
python-pyutil 3.3.2-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 884 kB
  • sloc: python: 7,198; makefile: 6
file content (52 lines) | stat: -rwxr-xr-x 2,110 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python
# -*- coding: utf-8-with-signature-unix; fill-column: 77 -*-
# -*- indent-tabs-mode: nil -*-

#  This file is part of pyutil; see README.rst for licensing terms.

import os, sys

from random import randrange

import argparse

def main():
    CHUNKSIZE=2**20

    parser = argparse.ArgumentParser(prog="randfile", description="Create a file of pseudorandom bytes (not cryptographically secure).")

    parser.add_argument('-b', '--num-bytes', help="how many bytes to write per output file (default 20)", type=int, metavar="BYTES", default=20)
    parser.add_argument('-f', '--output-file-prefix', help="prefix of the name of the output file to create and fill with random bytes (default \"randfile\"", metavar="OUTFILEPRE", default="randfile")
    parser.add_argument('-n', '--num-files', help="how many files to write (default 1)", type=int, metavar="FILES", default=1)
    parser.add_argument('-F', '--force', help='overwrite any file already present', action='store_true')
    parser.add_argument('-p', '--progress', help='write an "x" for every file completed and a "." for every %d bytes' % CHUNKSIZE, action='store_true')
    args = parser.parse_args()
                     
    for i in xrange(args.num_files):
        bytesleft = args.num_bytes
        outputfname = args.output_file_prefix + "." + str(i)

        if args.force:
            f = open(outputfname, "wb")
        else:
            flags = os.O_WRONLY|os.O_CREAT|os.O_EXCL | (hasattr(os, 'O_BINARY') and os.O_BINARY)
            fd = os.open(outputfname, flags)
            f = os.fdopen(fd, "wb")
        zs = [0]*CHUNKSIZE
        ts = [256]*CHUNKSIZE
        while bytesleft >= CHUNKSIZE:
            f.write(''.join(map(chr, map(randrange, zs, ts))))
            bytesleft -= CHUNKSIZE

            if args.progress:
                sys.stdout.write(".") ; sys.stdout.flush()

        zs = [0]*bytesleft
        ts = [256]*bytesleft
        f.write(''.join(map(chr, map(randrange, zs, ts))))

        if args.progress:
            sys.stdout.write("x") ; sys.stdout.flush()

if __name__ == "__main__":
    main()