0

I only want to run my program if the user inputs 'ready'.

Is there a better way to nest the entire program under an if statement such as:

if input_variable == 'ready': 
     [program] 

Is there something from the sys library that could help me?

Thanks in advance

Cahn Ex
  • 61
  • 1
  • 4
  • 11
  • a `while` is probably better than `if` but you want something more *fancy* I guess.. – Ma0 Jul 13 '17 at 13:47
  • 3
    `if not (input_variable == 'ready'): sys.exit()` – cs95 Jul 13 '17 at 13:47
  • I'd avoid `sys.exit()` and use the current code you have. If you put `sys.exit()` inside your actual program, you could end up exiting in some nasty ways. I can't think of any _real_ reasons to back up what I'm saying, but I have strong feelings about it. – byxor Jul 13 '17 at 13:50
  • Are there any methods that does the opposite of sys.exit() i.e. something that starts the program instead of exiting? – Cahn Ex Jul 13 '17 at 13:53
  • @byxor What do you mean by nasty ways? The process running the script is killed, that's it. – cs95 Jul 13 '17 at 13:53
  • while not input_variable == 'ready': pass [program] – Daniel Lee Jul 13 '17 at 13:53
  • They need to write the logic that decides whether or not to run `program`. I'm worried they'll mix it both inside and outside the program. There's no certainty that they'll do this, but `sys.exit()` gives me a bad feeling that they will. It's not an error with your suggestion, but it's a potential structural pitfall. Plus, I don't see why fully exiting is necessary. – byxor Jul 13 '17 at 13:54

2 Answers2

0
input_variable = ''
while input_variable != 'ready':
    input_variable = input()
[program]

With this you will keep asking for an input until the user types 'ready'

Ivan
  • 782
  • 11
  • 23
0

Coldspeed made the comment that you could put this at the top of your file:

if input_variable != 'ready':
    sys.exit()

That will exit the program if it doesn't get the expected variable. However, I personally prefer a different paradigm: put your program in a main function, and conditionally return:

def main(*argv):
  if input_variable != 'ready':
    return
  [program]

if __name__ == '__main__':
  main(*sys.argv)

There are a number of reasons to put your program in a main function. The most notable is that it allows you to import the file without actually executing it, which can be very useful for debugging.

ewok
  • 20,148
  • 51
  • 149
  • 254