Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause and wait for command input in a Python script

Tags:

python

Is it possible to have a script like the following in 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

Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.


What I come up with (inspired by the answer) is something like the following:

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.'
like image 666
FJDU Avatar asked Nov 21 '12 20:11

FJDU


3 Answers

if you are using Python 2.x: raw_input()

Python 3.x: input()

Example:

# Do some stuff in script variable = raw_input('input something!: ') # Do stuff with variable 
like image 142
Cameron Sparr Avatar answered Sep 25 '22 18:09

Cameron Sparr


The best way I know to do this is to use the pdb debugger. So put

import pdb

at the top of your program, and then use

pdb.set_trace()

for your "pause".

At the (Pdb) prompt you can enter commands such as

(Pdb) print 'x = ', x

and you can also step through code, though that's not your goal here. When you are done simply type

(Pdb) c 

or any subset of the word 'continue', and the code will resume execution.

A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.

like image 35
Andy Lorenz Avatar answered Sep 23 '22 18:09

Andy Lorenz


Waiting for user input to 'proceed':

The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:

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

Proceed after waiting pre-defined time:

Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.

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

Actual Debugger for executable Command Line:

Please see answers above on using pdb for stepping through code

Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code

like image 37
Kelton Temby Avatar answered Sep 21 '22 18:09

Kelton Temby