问题
My script currently uses sys.argv
to check for an input file provided to the program.
I am trying to utilise argparse
instead but I cant seem to get it to work. I was able to set it up and add an argument, but when I parse an argument, and print that parsed argument, I get a namespace. How can I get a string? Basically, I want to take the argument as a string, and open a file with that name.
Currently, my sys.argv
is:
filename = sys.argv[1]
f = open(filename, 'r')
My argparse
prints out a Namespace
as follows:
arg = parser.parse_args()
print arg
How can I use that to open a file? I want to use argparse
since the error handlign for arguments there is a lot easier.
回答1:
think its preferable (or something!) to use the with
statement to open the file like this:
# printfile.py
import argparse
parser = argparse.ArgumentParser(description="Opens a file and does cool stuff ^^")
parser.add_argument('filename', type=str, help="Path to file to open")
args = parser.parse_args()
with open(args.filename) as f:
print ' my uber cool file:'
print f.readlines()
specifying those keyword args also helps make a pretty -h help text option (which is neat neat)
[dlam@dlam-63221:~] $ python printfile.py -h
usage: printfile.py [-h] filename
Opens a file and does cool stuff ^^
positional arguments:
filename Path to file to open
回答2:
Print arg
followed by a dot followed by whatever name you assigned to the argument in the argparse
setup.
Example:
parser = argparse.ArgumentParser(description = 'Title you want')
parser.add_argument('-f', action = "store", dest = "fflag", type = str, help = "Filename to be used, stdin is default")
In this case, the file name will be preceded by -f
on the command line and will be accessible by parser.fflag
of type str
来源:https://stackoverflow.com/questions/12310631/using-argparse-as-opposed-to-sys-argv