All,

I have a personal script that I'm trying to write, and I've run into a small problem. The problem is that I want to be able to support a '-s' argument no matter where the argument is. I also want that argument to be allowed more than once. For example:

script.py firstargument secondargument -s thirdargument -s fourth fifth -s sixth

What I've tried isn't working. I've tried the following:

currentArg = 1
foldername = sys.argv[1:]

for folders in foldername:
    if "-s" in folders:
        newArg = currentArg + 1
        setType = str(sys.argv[newArg])
        function(setType)

What it's doing is that it's taking the -s as an argument and still passing that to the function. What I'd like it to above is see that the first '-s' is at the fourth position, add 1 to 4, and then setType is set to sys.argv[5]. I'd also like it to continue to loop through the arguments and find any '-s' and then use the next argument as the value. Any ideas?

Thanks!

if "-s" in foldername:
???

foldername is the variable that I'm putting all arguments in; hence foldername = sys.argv[1:]

The error that I get is:

WindowsError: [Error 3] The system cannot find the path specified: 'c:\-s/.'

Notice that it sees -s as an argument and tries to pass that as a folder, but I want it to pass the NEXT argument as the folder...

Write your own parser !

#!/usr/bin/env python
import sys

def handle_args(args):
    s = False
    for a in args:
        if a == '-s':
            if s:
                break
            else:
                s = True
        else:
            yield (s, a)
            s = False
    if s:
        raise RuntimeError('missing argument for -s')

for item in handle_args(sys.argv[1:]):
    print(item)

'''my output --->
(False, 'firstargument')
(False, 'secondargument')
(True, 'thirdargument')
(True, 'fourth')
(False, 'fifth')
(True, 'sixth')
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.