Home Backend Development Python Tutorial How to exit Python by pressing any key under Linux

How to exit Python by pressing any key under Linux

Feb 24, 2017 pm 03:48 PM

One day, a classmate in the group asked, in Python, when using input or raw_input, I have to press Enter after typing to get the input value. So how can I implement functions such as exiting and pausing with any key? I didn’t know it at the time. Think more about it, because I haven’t been exposed to python for a long time, mainly under Linux.

Of course, it will be slightly simpler under Windows system. If you install python environment under Windows system, the default module that comes with it is called msvcrt, import msvcrt, and then call msvcrt.getch() that is Can. The next step is to implement the python version under Linux to press any key to exit.

When I first learned Python, I always wanted to implement a program that can press any key to continue/exit (poisoned by .bat), but I couldn't write it. Recently, when I was learning Unix C, I found that it can be implemented through the termios.h library. I tried it and found that Python also has this library, so I finally wrote a program like this. The following is the code:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import termios
def press_any_key_exit(msg):
# 获取标准输入的描述符
fd = sys.stdin.fileno()
# 获取标准输入(终端)的设置
old_ttyinfo = termios.tcgetattr(fd)
# 配置终端
new_ttyinfo = old_ttyinfo[:]
# 使用非规范模式(索引3是c_lflag 也就是本地模式)
new_ttyinfo[3] &= ~termios.ICANON
# 关闭回显(输入不会被显示)
new_ttyinfo[3] &= ~termios.ECHO
# 输出信息
sys.stdout.write(msg)
sys.stdout.flush()
# 使设置生效
termios.tcsetattr(fd, termios.TCSANOW, new_ttyinfo)
# 从终端读取
os.read(fd, 7)
# 还原终端设置
termios.tcsetattr(fd, termios.TCSANOW, old_ttyinfo)
if __name__ == "__main__":
press_any_key_exit("按任意键继续...")
press_any_key_exit("按任意键退出...")
Copy after login

For other information about termios, please refer to the Linux manual:

man 3 termios
Copy after login

Also add the three modes of *nix terminal (excerpted from )

Canonical mode

Canonical mode, also known as cooked mode, is a common mode for users. Characters entered by the driver are saved in a buffer, and these buffers are only buffered when the Enter key is received. The characters are sent to the program. The buffered data allows the driver to implement the most basic editing functions. The specific keys assigned to these functions are set in the driver and can be modified through the stty command or the system call tcsetattr

Non-canonical mode

When the buffering and editing functions are turned off, the connection is placed in non-canonical mode. The terminal processor still performs specific character processing, such as processing Ctrl-C and newline characters. conversion, but the edit keys will have no meaning, so the corresponding input is treated as a regular data entry program needs to implement the editing functionality itself

raw mode

When all processing After being closed, the driver will pass the input directly to the program, and the connection will be in raw mode.

The above is the implementation method of Python under Linux introduced by the editor to press any key to exit. I hope it will be helpful to everyone It's helpful. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank you all for your support on the PHP Chinese website!

For more related articles on how to exit Python by pressing any key under Linux, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles