我一直在使用输入函数作为暂停脚本的一种方式:

print("something")
wait = input("Press Enter to continue.")
print("something")

有正式的方式吗?


当前回答

我假设您希望在没有输入的情况下暂停。

Use:

time . sleep(秒)

其他回答

通过这个方法,你可以通过按任何指定的键来恢复你的程序:

import keyboard
while True:
    key = keyboard.read_key()
    if key == 'space':  # You can put any key you like instead of 'space'
        break

同样的方法,但方式不同:

import keyboard
while True:
    if keyboard.is_pressed('space'):  # The same. you can put any key you like instead of 'space'
        break

注意:你可以通过在shell或cmd中写这个命令来安装键盘模块:

pip install keyboard

我有一个类似的问题,我使用信号:

import signal

def signal_handler(signal_number, frame):
    print "Proceed ..."

signal.signal(signal.SIGINT, signal_handler)
signal.pause()

因此,您为信号SIGINT注册了一个处理程序,并暂停等待任何信号。现在从你的程序外部(例如在bash中),你可以运行kill -2 <python_pid>,这将向你的python程序发送信号2(即SIGINT)。您的程序将调用已注册的处理程序并继续运行。

非常简单:

raw_input("Press Enter to continue ...")
print("Doing something...")

为了跨Python 2/3兼容性,你可以通过六个库使用输入:

import six
six.moves.input( 'Press the <ENTER> key to continue...' )

仅适用于Windows,请使用:

import os
os.system("pause")