使用 'argparse' 而不是 sys.argv [英] Using 'argparse' as opposed to sys.argv
问题描述
我的脚本当前使用 sys.argv
来检查提供给程序的输入文件.
My script currently uses sys.argv
to check for an input file provided to the program.
我正在尝试使用 argparse
代替,但我似乎无法让它工作.我能够设置它并添加一个参数,但是当我解析一个参数并打印该解析后的参数时,我得到了一个命名空间.我怎样才能得到一个字符串?基本上,我想将参数作为字符串,然后打开一个具有该名称的文件.
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.
目前,我的 sys.argv
是:
filename = sys.argv[1]
f = open(filename, 'r')
我的 argparse
打印出一个 Namespace
如下:
My argparse
prints out a Namespace
as follows:
arg = parser.parse_args()
print arg
如何使用它来打开文件?我想使用 argparse
因为参数的错误处理要容易得多.
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.
推荐答案
认为使用 with
语句打开文件更可取(或其他!):
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()
指定这些关键字参数也有助于制作一个漂亮的 -h 帮助文本选项(非常整洁)
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
这篇关于使用 'argparse' 而不是 sys.argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!