使用'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
:
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()
指定这些关键字args还有助于使-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屋!