1

I have a doubt regarding the implementation of a logic using python. In printer(), when the value of abort changes in line 10, is there a way for main() to know it and immediately break the while loop?

EDIT: abort becomes True if and only if something went wrong.

import time

abort = False

def printer():
    global abort
    print("I'm the printer")
    time.sleep(5)
    if somethingiswrong():
        print("I'm aborting here")
        abort = True
    time.sleep(2)
    print("I have aborted")

def main():
    global abort
    while not abort:
        print("In while loop")
        time.sleep(2)
        printer()
        if abort:
            break
        print("Printer killed me")
    print("Quitting")

if __name__ == "__main__":
    main()

I mean, the log output is now:

> In while loop
> I'm the printer
> I'm aborting here
> I have aborted
> Quitting

Is there a more optimized way to achieve an output of:

> In while loop
> I'm the printer
> I'm aborting here
> Quitting

I'm not an expert and am not familiar with any of the python shortcuts, hacks, tricks, etc. Any help would be great..!!

7
  • What do you need the loop and abort for? Your program has a very linear flow. Commented Oct 11, 2020 at 13:38
  • 2
    There is no way that an assignment to a global can do this. Did you consider throwing an exception? Commented Oct 11, 2020 at 13:39
  • You need to start printer in another thread for this to work Commented Oct 11, 2020 at 14:07
  • @quamrana Throwing an exception where? Commented Oct 11, 2020 at 14:10
  • @Mike67, won't another thread increase load? Commented Oct 11, 2020 at 14:10

2 Answers 2

1

To stop a function (printer) to run at some point you could either return or raise an exception there:

def printer():
    global abort
    print("I'm the printer")
    time.sleep(5)
    print("I'm aborting here")
    abort = True
    if abort:
      return
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

That is the current implementation I'm following. Is that the most optimized approach for this problem?
1

If you want to use exceptions to control the flow you can:

import time

def printer():
    global abort
    print("I'm the printer")
    time.sleep(5)
    if somethingiswrong():
        print("I'm aborting here")
        raise RuntimeError("I'm aborting here")
    time.sleep(2)
    print("I have aborted")

def main():
    while True:
        print("In while loop")
        time.sleep(2)
        try:
            printer()
        except RuntimeError:
            break
        print("Printer killed me")
    print("Quitting")

if __name__ == "__main__":
    main()

Output as required

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.