因此,我有一个简单的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 = ''
不能解决此问题的原因。
我不知道该如何解决这个问题,而且在任何地方都找不到解决方案。任何帮助将不胜感激。
编辑: 针对重复标记,由于我们的情况不同,这个问题也有所不同,但是我可以看到提到的另一个问题确实回答了我的问题。
答案 0 :(得分:1)
看起来您正在运行Python 2,因此应使用raw_input
而不是input
。
input
尝试根据本地代码将输入字符串评估为本地范围内的Python代码,这不是您想要的。