问题
I'm using python 3.5.1 and running my file through command prompt on windows. The arguments are being passed after the program is run; ie the program prompts for input based on a previously generated list.
I'm looking to read in multiple numbers on the same line separated by spaces. Python 2.X it wouldn't have been an issue with raw_input but this is proving to be a challenge.
selection = list(map(int,input("Enter items to archive (1 2 etc):").split(",")))
If I enter two different numbers on the same line:
Enter items to archive (1 2 etc):29 30 Traceback (most recent call last): File "G:\Learning\Python\need_to_watch.py", line 15, in selection = list(map(int,input("Enter items to archive (1 2 etc):").split(","))) File "", line 1 29 30 ^ SyntaxError: unexpected EOF while parsing
I gave up on a single line and tried just doing it in a loop but I get a different error
data=[]
while True:
entry = int(input('Item number : '))
data.append(entry)
if entry == 'q':
break
It tries to evaluate 'q' as a variable even though I haven't eval()'d anything.
This question says to just use input().split() but it would appear that this no longer works.... accepting multiple user inputs separated by a space in python and append them to a list
I could try and catch the EOF exception, but that doesn't seem like the right way to do it, nor should it be necessary.
回答1:
If you want to pass arguments to a python script, you may want to take a look at argparse instead: https://docs.python.org/3/library/argparse.html
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('integers', type=int, nargs='+')
args = parser.parse_args()
print(args.integers)
python script.py 1 2 3 4
[1, 2, 3, 4]
回答2:
entry = input('Enter items: ')
entry = entry.split(' ')
entry = list(map(int, entry))
print(entry)
Or more concisely:
entry = list(map(int, input('Enter items: ').split(' ')))
print(entry)
回答3:
You try to evaluate everything as an int
which is obviously not going to work. Try this instead:
data = []
while True:
entry = input('Item number : ')
if entry == 'q':
break
try:
data.append(int(entry))
except:
print("Not a valid number")
来源:https://stackoverflow.com/questions/35260739/python-3-5-1-read-multiple-inputs-into-an-array