# Buggy code
def main(fp=sys.stderr):
    """
    Paramters (internal use only)
    ---------
    fp  : file-like object for tqdm
    """
    d = tqdm.__init__.__doc__ + CLI_EXTRA_DOC

    opt_types = dict(RE_OPTS.findall(d))

    for o in UNSUPPORTED_OPTS:
        opt_types.pop(o)

    # d = RE_OPTS.sub(r'  --\1=<\1>  : \2', d)
    split = RE_OPTS.split(d)
    opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
    d = "".join(
        "\n  --{0}=<{0}>  : {1}{2}".format(*otd)
        for otd in opt_types_desc
        if otd[0] not in UNSUPPORTED_OPTS
    )

    d = (
        """Usage:
  tqdm [--help | options]

Options:
  -h, --help     Print this help and exit
  -v, --version  Print version and exit

"""
        + d.strip("\n")
        + "\n"
    )

    # opts = docopt(d, version=__version__)
    if any(v in sys.argv for v in ("-v", "--version")):
        sys.stdout.write(__version__ + "\n")
        sys.exit(0)
    elif any(v in sys.argv for v in ("-h", "--help")):
        sys.stdout.write(d + "\n")
        sys.exit(0)

    argv = RE_SHLEX.split(" ".join(sys.argv))
    opts = dict(zip(argv[1::2], argv[2::2]))

    tqdm_args = {"file": fp}
    try:
        for o, v in opts.items():
            try:
                tqdm_args[o] = cast(v, opt_types[o])
            except KeyError as e:
                raise TqdmKeyError(str(e))
        # fp.write('\ndebug | args: ' + str(tqdm_args) + '\n')
    except:
        fp.write("\nError:\nUsage:\n  tqdm [--help | options]\n")
        for i in sys.stdin:
            sys.stdout.write(i)
        raise
    else:
        buf_size = tqdm_args.pop("buf_size", 256)
        delim = tqdm_args.pop("delim", "\n")
        delim_per_char = tqdm_args.pop("bytes", False)
        if delim_per_char:
            with tqdm(**tqdm_args) as t:
                posix_pipe(sys.stdin, sys.stdout, "", buf_size, t.update)
        elif delim == "\n":
            for i in tqdm(sys.stdin, **tqdm_args):
                sys.stdout.write(i)
        else:
            with tqdm(**tqdm_args) as t:
                posix_pipe(sys.stdin, sys.stdout, delim, buf_size, t.update)


# Traceback (RuntimeError)
[s1758208@login04(eddie) ~]$ conda create -n test
[s1758208@login04(eddie) ~]$ conda activate test
(test) [s1758208@login04(eddie) ~]$ conda install python
Solving environment: done

## Package Plan ##

environment location: /exports/csce/eddie/ph/groups/rbm_ml/michael/myconda/envs/test

added / updated specs:
- python


The following packages will be downloaded:

package                    |            build
---------------------------|-----------------
python-3.6.4               |       hc3d631a_3        29.1 MB
libstdcxx-ng-7.2.0         |       hdf63c60_3         2.5 MB
certifi-2018.1.18          |           py36_0         144 KB
zlib-1.2.11                |       ha838bed_2         101 KB
sqlite-3.22.0              |       h1bed415_0         1.5 MB
wheel-0.30.0               |   py36hfd4bba0_1          67 KB
openssl-1.0.2n             |       hb7f436b_0         3.4 MB
libffi-3.2.1               |       hd88cf55_4          43 KB
libgcc-ng-7.2.0            |       hdf63c60_3         6.1 MB
ncurses-6.0                |       h9df7e31_2         920 KB
tk-8.6.7                   |       hc745277_3         3.2 MB
setuptools-38.5.1          |           py36_0         525 KB
pip-9.0.1                  |           py36_5         2.2 MB
libedit-3.1                |       heed3624_0         171 KB
ca-certificates-2017.08.26 |       h1d4fec5_0         263 KB
------------------------------------------------------------
Total:        50.2 MB

The following NEW packages will be INSTALLED:

ca-certificates: 2017.08.26-h1d4fec5_0
certifi:         2018.1.18-py36_0
libedit:         3.1-heed3624_0
libffi:          3.2.1-hd88cf55_4
libgcc-ng:       7.2.0-hdf63c60_3
libstdcxx-ng:    7.2.0-hdf63c60_3
ncurses:         6.0-h9df7e31_2
openssl:         1.0.2n-hb7f436b_0
pip:             9.0.1-py36_5
python:          3.6.4-hc3d631a_3
readline:        7.0-ha6073c6_4
setuptools:      38.5.1-py36_0
sqlite:          3.22.0-h1bed415_0
tk:              8.6.7-hc745277_3
wheel:           0.30.0-py36hfd4bba0_1
xz:              5.2.3-h55aa19d_2
zlib:            1.2.11-ha838bed_2

Proceed ([y]/n)? y


Downloading and Extracting Packages
python 3.6.4: ########################################################## | 100%
libstdcxx-ng 7.2.0: #################################################### | 100%
certifi 2018.1.18: ##################################################### | 100%

# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

Traceback (most recent call last):
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/exceptions.py", line 789, in __call__
return func(*args, **kwargs)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/cli/main.py", line 78, in _main
exit_code = do_call(args, p)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/cli/conda_argparse.py", line 77, in do_call
exit_code = getattr(module, func_name)(args, parser)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/cli/main_install.py", line 11, in execute
install(args, parser, 'install')
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/cli/install.py", line 255, in install
handle_txn(progressive_fetch_extract, unlink_link_transaction, prefix, args, newenv)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/cli/install.py", line 281, in handle_txn
progressive_fetch_extract.execute()
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/core/package_cache.py", line 584, in execute
exc = self._execute_actions(prec_or_spec, prec_actions)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/core/package_cache.py", line 599, in _execute_actions
progress_bar = ProgressBar(desc, not context.verbosity and not context.quiet, context.json)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/common/io.py", line 390, in __init__
self.pbar = tqdm(desc=description, bar_format=bar_format, ascii=True, total=1)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/_vendor/tqdm/_tqdm.py", line 388, in __new__
cls.monitor = TMonitor(cls, cls.monitor_interval)
File "/home/s1758208/miniconda3/lib/python3.6/site-packages/conda/_vendor/tqdm/_tqdm.py", line 83, in __init__
self.start()
File "/home/s1758208/miniconda3/lib/python3.6/threading.py", line 846, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread

# Fixed code
def main(fp=sys.stderr):
    """
    Paramters (internal use only)
    ---------
    fp  : file-like object for tqdm
    """
    try:
        log = sys.argv.index("--log")
    except ValueError:
        logLevel = "INFO"
    else:
        # sys.argv.pop(log)
        # logLevel = sys.argv.pop(log)
        logLevel = sys.argv[log + 1]
    logging.basicConfig(
        level=getattr(logging, logLevel),
        format="%(levelname)s:%(module)s:%(lineno)d:%(message)s",
    )
    log = logging.getLogger(__name__)

    d = tqdm.__init__.__doc__ + CLI_EXTRA_DOC

    opt_types = dict(RE_OPTS.findall(d))
    # opt_types['delim'] = 'chr'

    for o in UNSUPPORTED_OPTS:
        opt_types.pop(o)

    log.debug(sorted(opt_types.items()))

    # d = RE_OPTS.sub(r'  --\1=<\1>  : \2', d)
    split = RE_OPTS.split(d)
    opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
    d = "".join(
        "\n  --{0}=<{0}>  : {1}{2}".format(*otd)
        for otd in opt_types_desc
        if otd[0] not in UNSUPPORTED_OPTS
    )

    d = (
        """Usage:
  tqdm [--help | options]
Options:
  -h, --help     Print this help and exit
  -v, --version  Print version and exit
"""
        + d.strip("\n")
        + "\n"
    )

    # opts = docopt(d, version=__version__)
    if any(v in sys.argv for v in ("-v", "--version")):
        sys.stdout.write(__version__ + "\n")
        sys.exit(0)
    elif any(v in sys.argv for v in ("-h", "--help")):
        sys.stdout.write(d + "\n")
        sys.exit(0)

    argv = RE_SHLEX.split(" ".join(["tqdm"] + sys.argv[1:]))
    opts = dict(zip(argv[1::2], argv[2::2]))

    log.debug(opts)
    opts.pop("log", True)

    tqdm_args = {"file": fp}
    try:
        for o, v in opts.items():
            try:
                tqdm_args[o] = cast(v, opt_types[o])
            except KeyError as e:
                raise TqdmKeyError(str(e))
        log.debug("args:" + str(tqdm_args))
    except:
        fp.write("\nError:\nUsage:\n  tqdm [--help | options]\n")
        for i in sys.stdin:
            sys.stdout.write(i)
        raise
    else:
        buf_size = tqdm_args.pop("buf_size", 256)
        delim = tqdm_args.pop("delim", "\n")
        delim_per_char = tqdm_args.pop("bytes", False)
        if delim_per_char:
            tqdm_args.setdefault("unit", "B")
            tqdm_args.setdefault("unit_scale", True)
            tqdm_args.setdefault("unit_divisor", 1024)
            log.debug(tqdm_args)
            with tqdm(**tqdm_args) as t:
                posix_pipe(sys.stdin, sys.stdout, "", buf_size, t.update)
        elif delim == "\n":
            log.debug(tqdm_args)
            for i in tqdm(sys.stdin, **tqdm_args):
                sys.stdout.write(i)
        else:
            log.debug(tqdm_args)
            with tqdm(**tqdm_args) as t:
                posix_pipe(sys.stdin, sys.stdout, delim, buf_size, t.update)