获得用户输入

l--*_*''' 137 python user-input

我正在运行这个:

import csv
import sys
reader = csv.reader(open(sys.argv[0], "rb"))
for row in reader:
    print row
Run Code Online (Sandbox Code Playgroud)

我得到了回应:

['import csv']
['import sys']
['reader = csv.reader(open(sys.argv[0]', ' "rb"))']
['for row in reader:']
['    print row']
>>> 
Run Code Online (Sandbox Code Playgroud)

因为sys.argv[0]我希望它提示我输入文件名.

如何让它提示我输入文件名?

Dav*_*ebb 202

使用该raw_input()函数从用户(2.x)获取输入:

print "Enter a file name:",
filename = raw_input()
Run Code Online (Sandbox Code Playgroud)

要不就:

filename = raw_input('Enter a file name: ')
Run Code Online (Sandbox Code Playgroud)

或者如果在Python 3.x中:

filename = input('Enter a file name: ')
Run Code Online (Sandbox Code Playgroud)

  • 在Python 3中,它只是`input()` - __caution__:在2.x中也有一个输入方法,但是eval()是输入,因此是__evil__. (46认同)
  • 或者`raw_input("输入文件名:")` (15认同)
  • @Agostino`test:input = raw_input; 除了NameError:pass;`然后自由地使用`input`.(基本上,如果raw_input存在,则将其分配给名称输入.如果不存在,那么,您在python3中).分号实际上应该是换行符 (5认同)

Sun*_*mbi 114

在python 3.x中,使用input()而不是raw_input()

  • 一个很好的理由. (77认同)
  • @SilverRingvee`raw_input`不存在. (60认同)
  • 从3.x开始,`input()`比`raw_input()`更好吗?除了更容易键入... (4认同)

Nik*_*ohl 27

sys.argv[0]不是第一个参数,而是您当前正在执行的python程序的文件名.我想你想要的sys.argv[1]

  • 不是他要求的,但也很有用 (3认同)

Kyl*_*ner 8

为了将上述答案补充到一些可重复使用的东西,我想出了这个,如果输入被认为是无效的,它会继续提示用户.

try:
    input = raw_input
except NameError:
    pass

def prompt(message, errormessage, isvalid):
    """Prompt for input given a message and return that value after verifying the input.

    Keyword arguments:
    message -- the message to display when asking the user for the value
    errormessage -- the message to display when the value fails validation
    isvalid -- a function that returns True if the value given by the user is valid
    """
    res = None
    while res is None:
        res = input(str(message)+': ')
        if not isvalid(res):
            print str(errormessage)
            res = None
    return res
Run Code Online (Sandbox Code Playgroud)

它可以像这样使用,具有验证功能:

import re
import os.path

api_key = prompt(
        message = "Enter the API key to use for uploading", 
        errormessage= "A valid API key must be provided. This key can be found in your user profile",
        isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))

filename = prompt(
        message = "Enter the path of the file to upload", 
        errormessage= "The file path you provided does not exist",
        isvalid = lambda v : os.path.isfile(v))

dataset_name = prompt(
        message = "Enter the name of the dataset you want to create", 
        errormessage= "The dataset must be named",
        isvalid = lambda v : len(v) > 0)
Run Code Online (Sandbox Code Playgroud)


小智 7

使用以下简单方法通过提示交互式获取用户数据作为您想要的参数.

版本:Python 3.X

name = input('Enter Your Name: ')
print('Hello ', name)
Run Code Online (Sandbox Code Playgroud)