使用 argparse 访问多个文件
accessing multiple files using argparse
我正在尝试使用 argparse
:
读取文件数量
parser.add_argument(
'-f',
'--text-file',
metavar='IN FILE',
type=argparse.FileType('r'),
nargs='*')
...
...
args = parser.parse_args()
print args
当多个文件作为命令行参数传递时,只有最后一个文件出现在 args 中:
python example.py -o x.xml -s sss -c ccc -t "hello world" --report_failure -f ex.1 -f ex.2
Namespace(outputfile=<open file 'x.xml', mode 'w' at 0x028AD4F0>, report_failure=True, test_case='ccc', test_suite='sss', text='hello world', text_file=[<open file 'ex.2', mode 'r' at 0x028AD5A0>])
我做错了什么以及如何访问我从命令行传递的所有文件?
注意:我在 Windows.
上使用 python 2.7.6
复杂化的发生是因为您将多个参数传递给同一个参数 -f 并且每个参数都替换了它之前的参数。在这种情况下可行的是:
python example.py -o x.xml -s sss -c ccc -t "hello world"
--report_failure -f ex.1 ex.2
这会将 ex.1 和 ex.2 收集到一个列表中,这就是我假设您想要做的。
nargs 上的文档作为参考:
'*'. All command-line arguments present are gathered into a list. Note
that it generally doesn’t make much sense to have more than one
positional argument with nargs='', but multiple optional arguments
with nargs='' is possible.
我正在尝试使用 argparse
:
parser.add_argument(
'-f',
'--text-file',
metavar='IN FILE',
type=argparse.FileType('r'),
nargs='*')
...
...
args = parser.parse_args()
print args
当多个文件作为命令行参数传递时,只有最后一个文件出现在 args 中:
python example.py -o x.xml -s sss -c ccc -t "hello world" --report_failure -f ex.1 -f ex.2
Namespace(outputfile=<open file 'x.xml', mode 'w' at 0x028AD4F0>, report_failure=True, test_case='ccc', test_suite='sss', text='hello world', text_file=[<open file 'ex.2', mode 'r' at 0x028AD5A0>])
我做错了什么以及如何访问我从命令行传递的所有文件? 注意:我在 Windows.
上使用 python 2.7.6复杂化的发生是因为您将多个参数传递给同一个参数 -f 并且每个参数都替换了它之前的参数。在这种情况下可行的是:
python example.py -o x.xml -s sss -c ccc -t "hello world"
--report_failure -f ex.1 ex.2
这会将 ex.1 和 ex.2 收集到一个列表中,这就是我假设您想要做的。
nargs 上的文档作为参考:
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn’t make much sense to have more than one positional argument with nargs='', but multiple optional arguments with nargs='' is possible.