Reputation: 1007
I am looking for a way to parse the following commandline syntax using the argparse module in python3:
myapp.py [folder] [[from] to]
Meaning: The user may optionally define a folder, which defaults to cwd. Additionally the user may pass up to two integers. If only one number is given, it should be stored in the to
variable. This is similar to the syntax of the python builtin range()
.
e.g.:
myapp.py folder
myapp.py 10
myapp.py 5 10
myapp.py folder 5 10
myapp.py folder 10
Is that possible? If so, how?
Upvotes: 2
Views: 1571
Reputation: 6571
I couldn't see a way to do it without using a named argument for folder:
# usage: argparsetest2.py [-h] [--folder [FOLDER]] [to] [fr]
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--folder', dest='folder', nargs='?', default=os.getcwd())
parser.add_argument('to', type=int, nargs='?')
parser.add_argument('fr', type=int, nargs='?')
args = parser.parse_args()
print args
Upvotes: 0
Reputation: 2909
I'd also suggest parsing sys.argv yourself.
FWIW, I parse sys.argv even on projects where argparse or similar would work, because parsing sys.argv yourself plays nicely with pylint or flake8.
Upvotes: 0
Reputation: 309891
You can do something quite silly:
import argparse
import os
class MyAction(argparse.Action):
def __call__(self,parser,namespace,values,option_string=None):
namespace.numbers = []
namespace.path = os.getcwd()
for v in values:
if os.path.isdir(v):
namespace.path = v
else:
try:
namespace.numbers.append(int(v))
if len(namespace.numbers) > 2
parser.error("Barg2!!!")
except ValueError:
parser.error("Barg!!!")
p = argparse.ArgumentParser()
p.add_argument('stuff',nargs='*',action=MyAction)
n = p.parse_args()
print n
But if you're going to do this, you might as well just process sys.argv
yourself -- you should really consider using actual options here...
Upvotes: 1
Reputation: 179392
Use options; that's what they're there for (and what argparse
is good at parsing).
Thus, a syntax like
myapp.py [-F folder] [[from] to]
would make a lot more sense, and be easier to parse.
Upvotes: 1