我想使用argparse来解析它所知道的参数,然后保持其余不变。例如,我希望能够运行使用argparse保留参数
performance -o output other_script.py -a opt1 -b opt2
它使用-o
选项,并留下其余不变。
模块profiler.py确实有optparse了类似的事情,但因为我使用argparse我做:
def parse_arguments():
parser = new_argument_parser('show the performance of the given run script')
parser.add_argument('-o', '--output', default='profiled.prof')
return parser.parse_known_args()
def main():
progname = sys.argv[1]
ns, other_args = parse_arguments()
sys.argv[:] = other_args
这也似乎工作,但如果还other_script.py还发生了什么有一个-o
的标志?
有没有一般更好的方法来解决这个问题?
啊,不知道那个谢谢!如果没有标记,实际上很难理解我猜想的是什么,这不是一个简单的问题。 – 2012-01-31 18:00:18
应该明确的是,您需要使用'parse_known_args()'方法(至少在python3上)。 6) – krishonadish 2018-02-07 23:12:13