简体   繁体   English

Python可以使用raw_input接受Ctrl + [char]吗?

[英]Can Python Accept Ctrl+[char] using raw_input?

I am writing a command line interface in python that accepts a lot of user input. 我正在用python编写一个命令行界面,该界面接受很多用户输入。 For the values that I am querying the user about, there is a significant amount of "additional information" that I could display, but would rather only display if the user needed help with how to provide a value. 对于我要向用户查询的值,我可以显示大量的“附加信息”,而仅在用户需要有关如何提供值的帮助时才显示。

So I thought I would provide my usual raw_input prompt, but also try an accept some Ctrl-H type sequences to output this help info. 因此,我想我将提供我通常的raw_input提示符,但也尝试接受一些Ctrl-H类型的序列来输出此帮助信息。

Can Python accept this kind of input via raw_input in a terminal/shell? Python可以通过终端/外壳中的raw_input接受这种输入吗? It there another more proper way to do this (preferably in the stdlib)? 还有另一种更合适的方法(最好在stdlib中)吗?

No, python cannot accept this kind of input through raw_input . 不,python无法通过raw_input接受这种输入。 This is because you're thinking about sequences like: Ctrl-C , Ctrl-Z , etc. These are not keyboard inputs, these are signals that are processed by the terminal (not the program). 这是因为您正在考虑以下序列: Ctrl-CCtrl-Z等。这些不是键盘输入,这些是由终端 (不是程序)处理的信号

You can try to set up signal handlers that will do this for you, but that is not a very reliable solution (regardless of whether you're using python or something else). 您可以尝试设置将为您执行此操作的信号处理程序 ,但这并不是一个非常可靠的解决方案(无论您使用的是python还是其他工具)。

The best solution for accepting this kind of input is to either use curses , or use readline (with adjustments to the configuration to handle things like Ctrl-H ). 接受此类输入的最佳解决方案是使用curses或使用readline (对配置进行调整以处理Ctrl-H类的东西)。 Using readline will make your life much easier, but it comes with the cost that you have to license your program under the GNU GPL (or similar). 使用readline将使您的生活变得更加轻松,但是随之而来的是您必须根据GNU GPL(或类似协议)许可程序。 Whereas curses does not have this kind of restriction. 而诅咒则没有这种限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM