0

While trying to solve a bigger issue, I reduced my code to two simple commands and I found out that they are not executed in order.

My idea is to give a kind of feedback to the user after clicking on a button(3D Slicer) while running a function. So, what I would expect is to freeze the button immediately after clicking it until the action is finished. So I tried the following to check if the very first command is executed on first position:

def onStartSegmentation(self):
      self.segmentButton.setEnabled(False)

      sleep(3)
      print("2nd step: Starting segmentation")

However, the result is sleeping for 3 seconds and then executing both commands immediately one after the other.

I know this might sound silly, but I can't guess why it's acting like that.

  • 1
    Add `flush = True` to your print statements to force the flushing of the output stream. – SyntaxVoid Jul 25 '19 at 21:43
  • Is idle your primary editor or do you use notepad, npp or anything else. If you use some other editior please clarify how do you run your scripts from that editor. Do you work in python 2, 3? There are some specifications that are running specific, and having these information could help give you better answer. Also OS and bit platform can be of some benefits ( but this is rarely). – Danilo Jul 25 '19 at 21:45

1 Answers1

3

print() function is buffered. That means the output will be buffered before displaying to the screen until the buffer is full or new line character is encountered. If you want to have your output to be displayed on the screen immediately, you need to flush the buffer by using sys.stdout.flush() or you need to explicitly specify it in the argument to print function.

def onStartSegmentation(self):
      print("1st step: Starting segmentation", flush = True)

      sleep(3)
      print("2nd step: Starting segmentation", flush = True)

OR

def onStartSegmentation(self):
          print("1st step: Starting segmentation")
          sys.stdout.flush()

          sleep(3)
          print("2nd step: Starting segmentation")
          sys.stdout.flush()
Arco Bast
  • 3,595
  • 2
  • 26
  • 53
kadina
  • 5,042
  • 4
  • 42
  • 83
  • This still doesn't work for me. But anyway, what I was trying to do was giving feedback to the user while executing an order in 3D Slicer. For example, blocking the button after pressing it until it is executed. I tried with sys.stdout.flush() after stating to block the button, then sleeping for 3 seconds and finally printing the second statement. But the result is again freezing the button after sleeping 3 seconds. – Susan Mroz Jul 29 '19 at 20:34