Skip to content

Argparse

Ariel Balter edited this page Jan 5, 2017 · 4 revisions
if __name__ == "__main__":
    import argparse
    from argparse import RawTextHelpFormatter
    parser = argparse.ArgumentParser(
        formatter_class=RawTextHelpFormatter,
        description="""Generate lists of commands for ChIP - Seq analysis.
            1) Commands to create intersects of peaks from different replicates
            2) Commands to get the coverage for these intersects.""",
        )
    parser.add_argument('--config-file', '-cf',
        required=True,
        type=str,
        help="YAML configuration file"
        )
    parser.add_argument('--intersects', '-i',
        required=False,
        type=str,
        help="Filename for the list of intersection commands.",
        )
    parser.add_argument('--coverage', '-c',
        required=False,
        type=str,
        help="Filename for the list of coverage commands.",
        default=None
        )
    parser.add_argument('--fold', '-f',
        required=False,
        action="store_true",
        help="If included, fold and log-fold coverage will be calculated for intersects.",
        )
    args=parser.parse_args()

    sample_config_file=args.config_file
    intersects_commands_filename=args.intersects
    coverage_commands_filename=args.coverage
    fold = args.fold

    chipseq_config=ChipSeqConfiguration(sample_config_file)

    if intersects_commands_filename:
        chipseq_config.writeIntersectCommands(intersects_commands_filename)

    if coverage_commands_filename:
        chipseq_config.writeCoverageCommands(coverage_commands_filename)

    if fold:
        chipseq_config.writeFoldChange()

if __name__ == "__main__":

    import argparse

    parser = argparse.ArgumentParser(
        description='Count kmers in fastq files',
        epilog="""Tip: You can use this to create your reference. For instance
            run on your reference geneome without the --reference (-r)
            flag"""
        )
    parser.add_argument('--sample', '-s',
        required=True,
        type=str,
        help="The sample fastq file"
        )
   parser.add_argument('--outfile', '-o',
        required=False,
        type=str,
        help="output file",
        default=None
        )
    parser.add_argument('--kmer-length', '-k',
        required=True,
        type=int,
        help="kmer length"
        )
    parser.add_argument('--reference', '-r',
        required=False,
        type=str,
        help="reference kmer count file for normalized counts",
        default=None
        )

    args = parser.parse_args()

    #sys.exit()

    sample = args.sample
    outfilename = args.outfile
    kmer_length = args.kmer_length
    ref_countfile = args.reference

    #print("sample " + sample)
    #print("kmer_length " + str(kmer_length))

    ### Count kmers
    kmer_counts = countKmers(
        samplefile=sample,
        kmer_length=kmer_length
    )

    ### create outfile object or leave as None
    if outfilename != None:
        outfile = open(outfilename, 'w')
    else:
        print("No outfile specified. Writing to stdout.")

    if ref_countfile == None:
        print("Did not get a reference file. Not normalizing.")
        printKmerCounts(
            sample_kmer_counts=kmer_counts,
            outfile=outfile
        )
    else:
        print("Got reference file " + ref_countfile + ". Normalizing")
        printNormalizedKmerCounts(
            sample_kmer_counts=kmer_counts,
            ref_countfile=ref_countfile,
            outfile=outfile
        )
if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description='Find max and min of a specific column',
        epilog="""A future enhancement will be to handle multiple columns."""
        )
    parser.add_argument('--file', '-f',
        required=True,
        type=str,
        help="The input file"
        )
    parser.add_argument('--column', '-c',
        required=True,
        type=int,
        help="The column number, 1 indexed like `cut` and other shell tools.",
        )
    parser.add_argument('--delimiter', '-d',
        required=False,
        type=str,
        help="Column separator. Defaults to tab.",
        default="\t"
        )

    args = parser.parse_args()

    min, max = findMinMax(args.file, args.column, args.delimiter)

    print("{}\t{}".format(min, max))

Required Named Arguments

http://stackoverflow.com/a/24181138/188963

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT

Foo

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Output file name

required named arguments:
  -i INPUT, --input INPUT
                        Input file name
Clone this wiki locally