【问题标题】:Getting EOF error and not able to figure out the reason出现 EOF 错误并且无法找出原因
【发布时间】:2019-04-25 14:00:34
【问题描述】:

在下面的代码中,我收到了 EOF 错误。我无法弄清楚原因。如果我使用 input() 而不是 sys.stdin.read() 代码可以正常工作。我认为我的问题类似于链接 Python raw_input following sys.stdin.read() throws EOFError

当我执行 print(input_str) 时,它不会打印任何内容,控制台只是跳过一行。它不要求任何输入。 打印 input_list,生成下面给出的错误。 NameError: name 'input_list' 未定义。

import ast,sys
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)
C = input_list[0]
F = input_list[1]
H = input_list[2]
k=set(C).intersection(set(F)).intersection(set(H))

代码错误是:

Traceback (most recent call last):

  File "C:\Users\z003p4nk\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-14-dd3473bf412a>", line 5, in <module>
    input_list = ast.literal_eval(input_str)

  File "C:\Users\z003p4nk\AppData\Local\Continuum\anaconda3\lib\ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')

  File "C:\Users\z003p4nk\AppData\Local\Continuum\anaconda3\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)

  File "<unknown>", line unknown

    ^
SyntaxError: unexpected EOF while parsing

【问题讨论】:

  • 这是ast.literal_eval("") 的预期结果。您需要确保input_str 不为空。您可能应该使用input() 而不是sys.stdin.read(),因为表单需要一行输入,而后者读取直到您关闭标准输入。

标签: python python-3.x


【解决方案1】:

sys.stdin.read() 只会读入以 Ctrl-D 结尾的行,而input() 将在收到回车键后读入一行。正如 Chepner 所说,您必须使用 Ctrl-D 关闭标准输入,以便函数读取该行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2012-01-17
    • 2023-04-08
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多