1

I like how gdb and lldb can take two sets of arguments, one for gdb/lldb itself and one for the target application. For example:

lldb /bin/ls -- -al -foo=bar

On the left side of the double-dash '--' you can put your lldb arguments and on the right side you can put your target args. Is there a way to read two sets of arguments like this in my Python script?

2
  • well, just split the argument array: n = sys.argv.index('--'); left = sys.argv[:n]; right = sys.argv[n+1:] and catch ValueError when -- isn't found. Commented Dec 9, 2015 at 0:20
  • As @4ae1e1 points out, replace sys.argv with sys.argv[1:] in my comment above (best create another variable and use that) Commented Dec 9, 2015 at 0:51

1 Answer 1

1

Yes! ArgumentParser.parse_args() can optionally take a list of arguments, formatted similarly to what you see in sys.argv.

import sys
import argparse

first_parser = argparse.ArgumentParser()
first_parser.add_argument('arg1')

second_parser = argparse.ArgumentParser()
second_parser.add_argument('arg2')

first_args = []
second_args = []
double_dashed = False
for arg in sys.argv[1:]:
    if arg == '--':
        double_dashed = True
    elif not double_dashed:
        first_args.append(arg)
    else:
        second_args.append(arg)
print(first_parser.parse_args(first_args))
print(second_parser.parse_args(second_args))

This prints out:

$ ./example.py one -- two
Namespace(arg1='one')
Namespace(arg2='two')
Sign up to request clarification or add additional context in comments.

12 Comments

@4ae1e1, appending is efficient. It takes constant averaged time (with the common double-capacity strategy). Plus, there is absolutely no need to worry about performance of argument parsing.
@4ae1e1. Why do you keep claiming it is inefficient? Again, it takes constant averaged time, just like slicing.
@4ae1e1: To counter your false claims
And what's wrong with my comment now? Checked it and it works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.