1

I am trying to run a script with up to 8 arguments. For example:

pythonscript.py hello there howdy do argument5 argument6 argument7 argument8

I want to store arguments 5-8 in an array, however, if arguments 5-8 are not entered, I want a default value assigned to a variable. I don't care if it's a tuple, the data in the input will not change.

I have this so far, but can't get it to work. What am I missing?

import sys

try:
    values = (sys.argv[5],sys.argv[6],sys.argv[7],sys.argv[8])
except:
    values ='127.0.0.1'

2 Answers 2

1

Here's another way you could do it that doesn't require you to explicitly state the various elements of sys.argv:

import sys

if len(sys.argv) > 5:
    values = sys.argv[5:]
else:
    values = '127.0.0.1'

This takes advantage of Python's slicing syntax.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't quite see what's wrong here:

>>> import sys
>>> 
>>> try:
...     values = (sys.argv[5],sys.argv[6],sys.argv[7],sys.argv[8])
... except:
...     values ='127.0.0.1'
... 
>>> values
'127.0.0.1'

Please note that this is run from the python shell so the sys.argv aren't what you get if run from a script.

Could you post the error message, or data you get and the data you expect?

1 Comment

Bah! I'm a dummy. I was trying to work on a variable in a function, but was doing it out of sequence. Because I wasn't exiting the script gracefully on error, I wasn't able to print the contents of the array to confirm it was populating, so I assumed that my issue was the array population.

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.