【问题标题】:"SyntaxError: unexpected EOF while parsing" when using input()使用 input() 时出现“语法错误:解析时出现意外 EOF”
【发布时间】:2010-10-01 08:24:21
【问题描述】:

我有 2 个 Python 脚本,分别是 main_menu.py 和 inputip.py。

当我的函数在 inputip.py 中完成时,当我按“enter”重定向到 main_menu.py 时,就会出现问题。该脚本不允许我重定向到 main_menu.py,而是在 Windows 命令提示符下显示此错误:

Traceback (most recent call last):
  File "C:\python\main_menu.py", line 32, in ?
    execfile('C:\python\Inputip.py')
  File "C:\python\Inputip.py", line 11, in ?
    input ("\nSelect enter to proceed back to Main Menu\n")
  File "<string>", line 0

^ SyntaxError: 解析时出现意外的 EOF

这是我的代码(main_menu.py):

def menu():
#print what options you have
print "Welcome to Simple Network Program"
print " "
print "Please enter a following option to proceed"
print " "
print "2) View Personal IP Address"
print " "
return input ("Select an Option here: ")
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
    execfile('Inputip.py')
elif choice == 5:
    loop = 0
print "Thank you for using the Simple Network Program!"

代码(inputip.py):

#! /usr/bin/python

# To change this template, choose Tools | Templates
# and open the template in the editor.
import socket
import os
print ("\n\n"+socket.gethostbyname(socket.gethostname()))
input ("\nSelect enter to proceed back to Main Menu\n")

execfile('C:\python\main_menu.py')

错误似乎指向 execfile。关于代码的一些建议会很棒。谢谢!

【问题讨论】:

  • 请修正缩进并正确格式化回溯
  • 此外,您在不同模块上使用 execfile() 是否有原因?您是否还需要单独运行脚本?如果没有,只需使用 import。
  • 没有直接链接到原始问题的评论:您绝对应该避免在几乎所有情况下使用 execfile !改用对象和方法!

标签: python input syntax-error python-2.x


【解决方案1】:

除非您使用的是 python 3.x(但您的问题没有这样标记),否则不要使用输入。请改用 raw_input。它将返回字符串,因此先将它们转换为 int,或者进行字符串比较。例如

x = raw_input("Choice")
if x == '1': 
    do_this()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多