Hi everyone,

hope someone can help me or guide me since python really something new for me.

I use argv to read some input from user. My problem is i don't know how to read the input as a list. Assume that user should give --n and --file as input data.

>> number.py  --n 1 2 3 --file data.txt

I want to read this --n input. I tried this.

if a == "--n":
     n =(argv[:3])

But the problem the number length is unknown (depend on user). How do i handle this? Should be not difficult but since too many works make my brain frozen. Really need help. Many thanks before

Give this a try:

import sys

# there is a commandline
if len(sys.argv) > 1:
    mylist = []
    # sys.argv[0] is the program filename, slice it off
    for element in sys.argv[1:]:
        mylist.append(element)
else:
    print "usage %s element1 element2 [element3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were 1 2 3 4 5
# mylist should be ['1', '2', '3', '4', '5']
print(mylist)

Hi Uran,

many thanks for your quick reply. My problem is how to limit reading the user's input. In your solution you write :

for element in sys.argv[1:]:

The [:1] means the system read the input from this point until end.
The user input is not only number (this what i need to catch) but others more. It something like :

-n 1 2 3 4 -f abc.txt

The question is how to tell python to read after --n and not include -file .

Many thanks again.

In this case you have to set a flag like this:

import sys

# there is a commandline
if len(sys.argv) > 1:
    mylist = []
    # sys.argv[0] is the program filename, slice it off
    flag = False
    for element in sys.argv[1:]:
        if element == '-f':
            flag = False
        if flag == True:
            mylist.append(element)
        if element == '-n':
            flag = True


else:
    print "usage %s element1 element2 [element3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were -n 1 2 3 4 -f abc.txt
# mylist should be  ['1', '2', '3', '4']
print(mylist)
This question has already been answered. Start a new discussion instead.