DEV Community

Josua Blejeru
Josua Blejeru

Posted on • Edited on

Enhance your Python scripts

Maybe you remember some commands from documentations like:

brew upgrade && brew update
Enter fullscreen mode Exit fullscreen mode

Yea, you see right. This command will execute brew upgrade and brew update
one after another. But did you know you can do something similar to get the same result?

brew upgrade; brew update
Enter fullscreen mode Exit fullscreen mode

The difference between them is simple and has to do with status codes.

What are Statuscodes and how can I use them?

Here is a 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()
Enter fullscreen mode Exit fullscreen mode

"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 you command line:

python script.py && echo "finish"
Enter fullscreen mode Exit fullscreen mode

Nothing happend...right?

Now change sys.exit(0) with 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 controling your workflow in the CLI.

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

bash
python script.py; echo "finish"

The semicolumn is also used to execute one command after another, but our semicolumn don`t 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 preventing the executions of commands if something went wrong in your execution. Sometimes you need to know how your program has exit and sometimes you wish code get executed anyway... you decide!

If it was usefull for you please share it with a friend and leave a comment! Thanks!

Top comments (0)