【问题标题】:Press any key to continue (Python, Crossplatform solution)按任意键继续(Python,跨平台解决方案)
【发布时间】:2013-09-17 09:22:48
【问题描述】:

我正在尝试使用 Python 2.7.x 在 Linux/Mac/Windows 机器上创建脚本的一种行为。

在此线程的帮助下:

我可以达到预期的效果:按任意键脚本都会退出。

但也许有更好的方法来做到这一点?有人可以帮帮我吗?

谢谢!

#!/usr/bin/env python2.7

import os
import sys

def wait_for_press():
    if sys.platform == 'win32':
        os.system("pause")
    elif sys.platform in ('linux2', 'darwin'):
        import termios
        import tty

        print "Press any key to continue..."

        stdin_file_desc = sys.stdin.fileno()
        old_stdin_tty_attr = termios.tcgetattr(stdin_file_desc)
        try:
            tty.setraw(stdin_file_desc)
            sys.stdin.read(1)
        finally:
            termios.tcsetattr(stdin_file_desc, termios.TCSADRAIN, old_stdin_tty_attr)

if __name__ == "__main__":
    wait_for_press()

【问题讨论】:

    标签: python python-2.7 cross-platform stdin fcntl


    【解决方案1】:

    哎呀。为什么你有特定于操作系统的代码?如果有人使用'linux3'会发生什么? 您可能正在寻找 curses 库。

    请参阅 nachik 在Python read a single character from the user 上的回答

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      相关资源
      最近更新 更多