How to pause and wait for command input in a python script
python中是否可能有如下脚本?
1 2 3 4 5 6 7 8 | ... 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命令行解释器,并在用户以某种方式完成该部分后继续执行。
编辑:
我想到的(受答案启发)如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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.' |
如果您使用的是python 2.x:
python 3.x:
例:
1 2 3 | # do some stuff in script variable = raw_input('input something!: ') # do stuff with variable |
我所知道的最好方法是使用pdb调试器。所以放
1 | import pdb |
在程序顶部,然后使用
1 | pdb.set_trace() |
为您的"暂停"
在(Pdb)提示符下,您可以输入以下命令
1 | (Pdb) print 'x = ', x |
您也可以单步执行代码,尽管这不是您的目标。完成后,只需键入
1 | (Pdb) c |
或单词" continue"的任何子集,代码将恢复执行。
截至2015年11月,调试器的简介非常简单
https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/
但是,如果您使用Google" python调试器"或" python pdb",那么当然会有很多此类资源。
我认为您正在寻找这样的东西:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import re # Get user's name name = raw_input("Please enter name:") # While name has incorrect characters while re.search('[^a-zA-Z\ ]',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:") |
只需使用input()函数,如下所示:
1 2 3 | # 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 |
由于该问题的SEO,我添加了另一个与"暂停"和"等待"有关的答案。
等待用户输入"继续":
输入函数的确会停止脚本的执行,直到用户执行某项操作为止,以下示例显示了在查看预定的目标变量后如何手动继续执行:
1 2 3 | var1 ="Interesting value to see" print("My variable of interest is {}".format(var1)) key_pressed = input('Press ENTER to continue: ') |
等待预定义的时间后继续:
我发现另一个有用的情况是延迟一下,以便我可以读取以前的输出并决定是否按ctrl + c结束脚本,如果我不希望脚本在某个时候终止,则继续执行。
1 2 3 4 5 | 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 |
可执行命令行的实际调试器:
请参阅上面关于使用
参考:https://www.pythoncentral.io/pythons-time-sleep-pause-wait-sleep-stop-your-code/