【问题标题】:Why does the thread end without waiting for input?为什么线程不等待输入就结束了?
【发布时间】:2019-10-05 10:16:22
【问题描述】:

“你叫什么名字?”打印了五次,但我无法让 input() 工作。为什么程序在不需要五个用户输入的情况下结束?使用线程时 - 如何获得 5 个输入?

import threading

def user_input():
    print("Inside user_input")
    ui = input("What's your name? ")
    return ui

threads = []
for i in range(5):
    t = threading.Thread(target=user_input)
    threads.append(t)
    t.start()

【问题讨论】:

  • 因为主线程已经退出导致程序终止。
  • 你必须join()你的线程。
  • @selbie 和@KlausD,如果线程不是守护线程(它们不是),它们应该继续运行,即使 主线程终止。当我运行它时,输入所有 5 个输入没有问题。当我将 return ui 语句更改为 print(ui) 语句时,我看到了输入的内容。
  • 看到它在工作here(尽管时间确实不同)。
  • here 调用sleep 以确保主线程已终止。

标签: python multithreading input


【解决方案1】:

尝试less code,如下。这适用于linux。贴出的代码在windows上不行,在linux上可以。

输入代码:

import threading

def user_input():
    input("What's your name? ")

threads = []
for i in range(5):
    t = threading.Thread(target=user_input)
    threads.append(t)
    t.start()

输出:

Python 3.7.4 (default, Jul  9 2019, 00:06:43)
[GCC 6.3.0 20170516] on linux
What's your name? test
What's your name? test
What's your name? test
What's your name? test

【讨论】:

  • 答案的哪一部分有错误的缩进?开始,代码还是输出?
  • input("What's your name? ") 需要缩进,for i in range(5): 下的三行需要缩进。您为什么不尝试复制和粘贴您发布的内容并尝试在被否决之前运行它。
  • 此外,据我所知,您的代码与 OP 之间的唯一区别是删除了 print("Inside user_input") 和一个无害的 return 语句。正如我评论的那样,我实际上发现 OP 的代码可以在我的 Windows 平台上运行。
  • OP 的代码挂在我的 Windows 10 上。Python exe 目录、python 脚本目录、path 和 pathext 有 python 添加,python._pth 有所有目录。尽管删除了星号'n',但我让它在linux上工作。此外,通过与 python 脚本目录中的其他脚本一起使用的脚本编辑器运行。
  • 我仍在使用 Windows 7。
猜你喜欢
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 2021-11-03
  • 2015-05-15
  • 1970-01-01
相关资源
最近更新 更多