首页 > 解决方案 > 为什么我在输入过程中必须按三下 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)

标签: python

解决方案


推荐阅读