【问题标题】:input() not accepting anything [duplicate]输入()不接受任何东西[重复]
【发布时间】:2018-09-21 10:25:57
【问题描述】:

所以我有一个简单的 python 程序,它运行一个启动 php 内置服务器的命令。它一直有效,但我决定添加一段代码,让我在本地托管和公开托管之间进行选择。这段代码在箭头(/\ \/)内:

#Import the os package so that this code can run commands
import os

#Get the port that the user wants to host on
port = str(input("What port would you like to host on? "))

#\/\/\/\/\/\/\/\/\/\/\/
#Decide whether or not to make public or private
choice = ''
tupleL = ('l', 'L')
tupleP = ('p', 'P')
while True:
    choice = str(input("Type 'L' to host locally or 'P' to host publicly: "))

    if choice in tupleL:
        host = "localhost"
        break
    elif choice in tupleP:
        host = str(input("What is your global IP address? "))
        break
    else:
        print "That wasn't an option!"
#/\/\/\/\/\/\/\/\/\/\/\

#Add wanted port and host to the command that hosts the php server
cmd = "php -S " + host + ":" + port

#Actually run the command to host the php server
os.system(cmd)

choice = str(input("Type 'L' to host locally or 'P' to host publicly: ")) 之前一切正常。每当我放入任何东西时,无论它是什么,我都会得到:

What port would you like to host on? 8080
Type 'L' to host locally or 'P' to host publicly: a
Traceback (most recent call last):
  File "host_php.py", line 13, in <module>
    choice = str(input("Type 'L' to host locally or 'P' to host publicly: "))
  File "<string>", line 1, in <module>
NameError: name 'a' is not defined

我最初在input() 将字符串作为对象时遇到了问题,但我通过使用str(input()) 轻松解决了这个问题。我能想到的唯一可能的原因是我没有定义变量choice,但这不是原因,因为放置choice = '' 没有解决这个问题。

我不知道我应该如何解决这个问题,而且我还没有在任何地方找到解决方案。任何帮助将不胜感激。

编辑: 针对重复标记,由于我们的情况不同,这个问题有所不同,但我可以看到提到的其他问题确实回答了我的问题。

【问题讨论】:

标签: python string input


【解决方案1】:

看起来您正在运行 Python 2,因此您应该使用 raw_input 而不是 input

python 2 中的input 尝试将输入字符串评估为本地范围内的 Python 代码,根据您的代码,这不是您想要的。

【讨论】:

  • 我正在使用 Visual Studio 代码运行 Python 3.6 64 位,但它不允许我使用 raw_input
  • 啊,我刚刚切换到使用 Python 2.7 进行处理,它正在工作!谢谢。
猜你喜欢
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多