Using argparse to enter a file name

Hi, I'm trying to use argparse to enter a name from the command line, but I'm struggling to get it working.

I want to take the line passed from the command line (-d) that matches the file name (datbase.csv) and save it in the variable inputargs.snp_database_location.

This is used to enter my load_search_snaps function, as shown in my code below, which opens a file and does the stuff (pseudocode) for it.

    import csv, sys, argparse

    parser = argparse.ArgumentParser(description='Search a list of variants against the in house database')
    parser.add_argument('-d', '--database',
        action='store',
        dest='snp_database_location',
        type=str,
        nargs=1,
        help='File location for the in house variant database',
        default='Error: Database location must be specified')

    inputargs = parser.parse_args()

    def load_search_snps(input_file):
        with open(input_file, 'r+') as varin:
            id_store_dictgroup = csv.DictReader(varin)
            #do things with id_store_dictgroup                                                                          
        return result

    load_search_snps(inputargs.snp_database_location)

using the command in bash:

python3 snp_freq_V1-0_export.py -d snpstocheck.csv

I get the following error when trying to transfer its regular csv file from the same directory using the command line:

"snp_freq_V1-0_export.py", 33, load_search_snps      (input_file, 'r +') varin: TypeError: : ['snpstocheck.csv']

script, . , snp_database_location, , . , ?

+4
1

nargs=1 inputargs.snp_database_location ( ), .

In [49]: import argparse

In [50]: parser = argparse.ArgumentParser()

In [51]: parser.add_argument('-d', nargs=1)
Out[51]: _StoreAction(option_strings=['-d'], dest='d', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None)

In [52]: args = parser.parse_args(['-d', 'snpstocheck.csv'])

In [53]: args.d
Out[53]: ['snpstocheck.csv']

, nargs=1.

+4

Source: https://habr.com/ru/post/1525433/


All Articles