【问题标题】:How can I work with input flow in Pycharm?如何在 Pycharm 中使用输入流?
【发布时间】:2016-03-27 18:33:28
【问题描述】:

我是 Python 新手,使用 Pycharm 处理代码。

我正在编写一个简单的程序,它读取字符串,然后将其转换为 int。

import sys

    print ("Hello word")
    data = sys.stdin.read()
    tokens = data.split()

    for i in range(len(tokens)):
        tokens[i] = int(tokens[i])

    print (tokens[1])

我运行程序,输入了三个数字,但仅此而已 为什么,运行程序时看不到打印结果?

【问题讨论】:

    标签: python python-3.x pycharm


    【解决方案1】:

    这是因为程序仍在读取stdin。要从stdin 中只读取一行,您必须使用stdin.readline()。如果您在sys.stdin.read() 行之后运行带有断点的调试过程,您将看到程序永远不会到达它。例如,在 Ideone 中运行您的程序,它允许您在运行应用程序之前指定标准输入,stdin.read() 工作正常。通常它会一直读取到 EOF(文件结束)。因此,要么使用sys.stdin.readline()(内置input() 就是这样做的),或者如果你想读取多行,则使用文件输入。如果您真的想使用sys.stdin.read(),也可以参考this 的帖子了解更多信息。

    【讨论】:

      【解决方案2】:

      您已经用.read() 有效地阻止了该程序;使用input() 更简单,像这样:

      print('Hello World')
      data = input()
      tokens = map(int, data.split()) # this converts to int
      print(tokens[1])
      

      【讨论】:

        猜你喜欢
        • 2018-10-25
        • 2016-06-04
        • 2015-04-29
        • 2021-11-16
        • 2018-09-16
        • 2020-03-30
        • 1970-01-01
        • 2014-12-27
        • 1970-01-01
        相关资源
        最近更新 更多