Using 'argparse' as opposed to sys.argv

情到浓时终转凉″ 提交于 2019-12-22 18:34:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!