prateek goyal prateek goyal - 10 months ago 40
Python Question

Not understanding return behavior in python

I was just trying a simple code:

import sys

def main():
print "this is main"
return "string1"

if __name__ == "__main__":

And when I run this piece of code, it gives random result, sometimes "string1" before "this is main" and sometimes after it.

Why is it so?

2 sample outputs:

this is main


Process finished with exit code 1



this is main

Process finished with exit code 1

Answer Source

sys.exit takes the return value of main() and produces it as the error code of the application. The value should usually be numeric, though Python is being a bit tricky here.

From the documentation of sys.exit:

If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

So what may be happening is a race between flushing of stdout (for print) and the output to stderr as specified above.

I suggest you try to flush stdout after the print (sys.stdout.flush) and see if you get consistent output that way.