Để có được chính xác những gì bạn đang tìm kiếm, các trick là sử dụng parse_known_args()
thay vì parse_args()
:
#!/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")
opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder (opts[1] is a list (possibly empty) of all remaining args)
if opts[1]: print('You passed the strings %s' % opts[1])
EDIT:
Đoạn mã trên sẽ hiển thị thông tin trợ giúp sau:
./clargs.py -h
usage: clargs_old.py [-h] [-a] [-b]
optional arguments:
-h, --help show this help message and exit
-a
-b
Nếu bạn muốn thông báo cho người dùng về đối số tùy ý tùy chọn, giải pháp duy nhất tôi có thể nghĩ là phân lớp ArgumentParser và viết nó vào chính bạn.
Ví dụ:
#!/bin/env python
import os
import argparse
class MyParser(argparse.ArgumentParser):
def format_help(self):
help = super(MyParser, self).format_help()
helplines = help.splitlines()
helplines[0] += ' [FOO]'
helplines.append(' FOO some description of FOO')
helplines.append('') # Just a trick to force a linesep at the end
return os.linesep.join(helplines)
parser = MyParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")
opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder
if opts[1]: print('You passed the strings %s' % opts[1])
nào hiển thị thông tin trợ giúp sau:
./clargs.py -h
usage: clargs.py [-h] [-a] [-b] [FOO]
optional arguments:
-h, --help show this help message and exit
-a
-b
FOO some description of FOO
Lưu ý việc bổ sung các [FOO]
trong "sử dụng" dòng và FOO
trong sự giúp đỡ dưới "đối số tùy chọn ".
Bạn đã đi qua hướng dẫn của argparse chưa? Tất cả mọi thứ bạn đang mô tả là có – SheetJS
Phần duy nhất không được thảo luận iirc là hành vi 'nargs =" * "' (để một đối số vị trí có thể lấy tất cả các đối số còn lại) – SheetJS
@Nirk, Điều phức tạp là nếu bạn chỉ sử dụng 'parse_args', ngay sau khi nó thấy đối số" vị trí ", nó dừng tìm kiếm các đối số khác và thu thập các đối số từ đối số vị trí đến cuối. Điều này là tốt trong hầu hết các trường hợp, nhưng sẽ phá vỡ ví dụ đầu tiên và thứ 3 của mình. – jedwards