user63019
user63019

Reputation: 33

How can I store user input from command line in Python?

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'

Upvotes: 1

Views: 1399

Answers (2)

JAB
JAB

Reputation: 21079

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.

Upvotes: 1

serverhorror
serverhorror

Reputation: 816

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?

Upvotes: 0

Related Questions