如何在python脚本中暂停和等待命令输入

时间:2012-11-21 20:15:26

标签: python

是否可以在python中使用如下的脚本?

...
Pause
->
Wait for the user to execute some commands in the terminal (e.g. 
  to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script

本质上,脚本暂时将控件提供给python命令行解释器,并在用户以某种方式完成该部分之后恢复。

编辑: 我想出的(受答案启发)如下:

x = 1

i_cmd = 1
while True:
  s = raw_input('Input [{0:d}] '.format(i_cmd))
  i_cmd += 1
  n = len(s)
  if n > 0 and s.lower() == 'break'[0:n]:
    break
  exec(s)

print 'x = ', x
print 'I am out of the loop.'

5 个答案:

答案 0 :(得分:27)

如果您使用的是python 2.x:raw_input()

python 3.x:input()

示例:

# do some stuff in script
variable = raw_input('input something!: ')
# do stuff with variable

答案 1 :(得分:6)

我知道这样做的最好方法是使用pdb调试器。所以把

import pdb

在程序的顶部然后使用

pdb.set_trace()

为你的“暂停” 在(Pdb)提示符下,您可以输入

等命令
(Pdb) print 'x = ', x

你也可以单步执行代码,虽然这不是你的目标。完成后,只需输入

即可
(Pdb) c 

或单词'continue'的任何子集,代码将继续执行。

截至2015年11月,对调试器的一个很好的简单介绍是 https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/ 但是如果你谷歌'python debugger'或'python pdb',当然有很多这样的来源。

答案 2 :(得分:2)

我认为你在寻找这个:

import re

# Get user's name
name = raw_input("Please enter name: ")

# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):

    # Print out an error
    print("illegal name - Please use only letters")

    # Ask for the name again (if it's incorrect, while loop starts again)
    name = raw_input("Please enter name: ")

答案 3 :(得分:0)

由于这个问题的SEO,我加入了另一个与“暂停”和“等待”有关的答案。

等待用户输入“继续”:

输入函数实际上将停止脚本的执行,直到用户执行某项操作为止,下面的示例显示了在查看预定的目标变量后如何手动继续执行:

var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')

等待预定时间后继续:

我发现另一个有用的情况是延迟,这样我就可以读取以前的输出并决定是否要在某个好的点终止脚本,而选择ctrl + c,但是如果我什么都不做则继续。 / p>

import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds

可执行命令行的实际调试器:

有关使用pdb逐步浏览代码的信息,请参见上面的答案

参考:https://www.pythoncentral.io/pythons-time-sleep-pause-wait-sleep-stop-your-code/

答案 4 :(得分:0)

只需使用input()函数,如下所示:

# Code to be run before pause
input() # Waits for user to type any character and
        # press Enter or just press Enter twice

# Code to be run after pause