Pergunta

I'm new to python, and I'm currently trying to figure out how to open up multiple files using argparse. From the past questions posted here, it seems most people are asking to only open one file, which I used as the basis for my sample code. My sample code is:

import sys
import argparse 


parser = argparse.ArgumentParser(description="Compare two lists.")
parser.add_argument('infile1', type = file)
parser.add_argument('infile2', type = file) 
parser.add_argument('--same', help = 'Find those in List1 that are the same in List2')
parser.add_argument('--diff', help = 'Find those in List2 that do not exist in List2')
parser.parse_args()

data1 = set(l.rstrip() for l in open(infile1))
data2 = set(l2.rstrip() for l2 in open(infile2))

What is the correct way to use argparse over two text files? '-h' works as intended, but otherwise I get an error saying error: argument --same: expected one argument.

P.S. Eventually I will replace the two set commands to with/open

Foi útil?

Solução

1) The way you define --same and --diff they require an argument to follow them that would be assigned to the parsed arguments namespace. To make them boolean flags instead, you change that action by specifying the keyword argument action='store_true':

parser.add_argument('--same',
                    help='Find those in List1 that are the same in List2',
                    action='store_true')

2) You don't store the parsed arguments in a variable, and you're trying to refer to them as locals instead of on the object returned by parse_args():

args = parser.parse_args()

if args.same:
   # ...

3) If you specify type=file for the argument, the parsed argument will actually already be an opened file object - so don't use open() on it:

data1 = set(l.rstrip() for l in args.infile1)

Note: Currently a user can legally specify both --same and --diff, so your program needs to deal with that. You'll probably want to make those flags mutually exclusive.

Outras dicas

because per default add_argument() is for an argument that takes a parameter (try --help), but you have to set action=store_true.

parser.add_argument('--same', help = 'Find those in List1 that are the same in List2', action='store_true')

here's your --help:

>>> parser.parse_args(['--help'])
usage: [-h] [--same SAME] [--diff DIFF] infile1 infile2

Compare two lists.

positional arguments:
  infile1
  infile2

optional arguments:
  -h, --help   show this help message and exit
  --same SAME  Find those in List1 that are the same in List2
  --diff DIFF  Find those in List2 that do not exist in List2

and once your arguments are parsed, you access them as members of args:

data1 = set(l.rstrip() for l in open(args.infile1))
data2 = set(l2.rstrip() for l2 in open(args.infile2))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top