有没有办法通过软件将 Ctrl+D 发送到 python 标准输入?

Is there a way to send a Ctrl+D via software in to python stdin?

我使用 lexer.input(sys.stdin.read()) 能够自由地在控制台中写入并在词法分析器中标记 if´s、for´s 等,但我希望当有人写入 "exit" 时它会发送 CTRL +D so sys.stdin.read() 停止阅读并结束我的程序。 试图在我的代码中这样做:

lexer.input(sys.stdin.read())
for tok in lexer:
    if tok.value == "exit":
        sys.stdin.read(0o4)

但它没有退出。 004 是因为在这个页面 https://mail.python.org/pipermail/python-list/2002-July/165325.html 他们说了 CTRL+D 的代码是什么,但没有说明如何发送它。

sys.stdin.read()会在返回前读取所有的stdin,所以

中的输入函数
lexer.input(sys.stdin.read())

不能被词法分析器内部的任何操作提前终止。在调用 lexer.input 之前,整个输入已被读取。

您最多可以阅读(但不包括)包含 exit 的第一行,内容如下:

from itertools import takewhile
lexer.input(''.join(takewhile(lambda line: 'exit' not in line, sys.stdin)))

虽然我个人更喜欢

from itertools import takewhile
notdone = lambda line: not line.lstrip().startswith('exit')
lexer.input(''.join(takewhile(notdone, sys.stdin)

这不会被中间恰好包含 exit 的行混淆,但如果遇到第一个单词刚好以 exit 开头的行,它仍然会停止。 (幸运的是,标准英语中唯一的此类词是词 exit 本身的简单变体。)