python - 为什么我在输入过程中必须按三下 CTRL-D 才能退出程序?
问题描述
这是一个简单的 Python 程序:
s = input('Name: ')
我运行程序,输入了几个字母,然后按下Ctrld:
$ python3 myscript.py
Name: myverylongna
什么也没发生,所以我再按Ctrld一次。什么都没发生。然后我第三次按下Ctrld。Python 终于退出了。我使用 Python 2.7 观察到相同的行为。
我不明白为什么我必须按Ctrld三下才能退出 Python。为了比较,我写了一个 C 程序来询问用户输入(警告:代码有很多错误):
#include <stdlib.h>
#include <stdio.h>
/* Asks the user for string input.
* Returns a pointer to the string entered by the user.
* The pointer must be freed.
*/
char* input()
{
char *s = malloc(sizeof(char));
if (s == NULL) {
fprintf(stderr, "Error: malloc\n");
exit(1);
}
char ch;
size_t s_len = 0;
while((ch = (char) getchar()) != '\n' && ch != EOF) {
s[s_len] = ch;
s_len++;
s = realloc(s, (s_len + 1) * sizeof(char));
if (s == NULL) {
fprintf(stderr, "Error: realloc\n");
exit(1);
}
}
s[s_len] = '\0';
return s;
}
int main()
{
printf("Name: ");
char *s = input();
free(s);
return 0;
}
C 程序只需要按两次Ctrld即可进行类似的输入。为什么?
Ctrld当用户在输入提示符处输入字符时,为什么python需要按三下才能退出程序?
(我在 Ubuntu 18.04 上运行 Python 3.6.8)
解决方案
推荐阅读
- javascript - 如何处理来自具有多种内容类型的外部 API 的响应
- android - 如何在选项卡式活动中更改不同的 URL 或视图?
- c# - 我的 C# dotnet 代码创建的 SQLite 数据库在哪里?(在 Mac 上)
- php - 如何将一条信息插入到已经存在的记录中?
- angular - 如何检查 ngFor 内部的条件
- php - 不识别表中的id
- spring - Spring Security 中的 Tomcat 错误(Spring + MySQL)
- google-cloud-platform - Keras 模型在 AI 平台训练中不使用 GPU
- google-apps-script - window.location.href = window.location.href 返回一个空白页
- javascript - 删除和添加 TextGeometry 会冻结场景