Enhance your Python workflow in the CLI

You may remember some commands from documentations like:

brew upgrade && brew update

This command will execute brew upgrade and brew update one after the other. But did you know that you can do something similar to get the same result?

brew upgrade; brew update

The difference between the two approaches is simple and has to do with status codes.

What are status codes and how can I use them?

Here is an example:

# script.py
import sys
import time
def doSomething():
for i in range(5):
time.sleep(1)
print("done")
sys.exit(0)
if __name__ == "__main__":
doSomething()

“Ok ok… I get it… but wait!”

Exactly. sys.exit(0) is used to exit a program and returns a status code of 0.

Try to run this command in your command line:

python script.py && echo "finish"

Nothing happened, right?

Now change sys.exit(0) to sys.exit(1) and rerun it.

This is the point where you will expect to see “finish” after the “4”, but && is preventing the execution because of the status code of 1.

You see… status codes can help control your workflow in the CLI.

Maybe you don’t care how your program is ending, so try this instead:

python script.py; echo "finish"

The semicolon is also used to execute one command after another, but our semicolon does not care about the status of the last executed program.

Conclusion

I think at this point the difference should be clear.

Both operators can help you prevent the execution of commands if something went wrong in your execution. Sometimes, you need to know how your program has exited, and sometimes you wish the code got executed anyway… you decide!

If this was useful for you, please share it! Thanks!

Attributions:
  1. undefined by undefined