Not understanding return behavior in python
<p>I was just trying a simple code:</p>

<pre><code>import sys

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

if __name__ == "__main__":
    sys.exit(main())
</code></pre>

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

<p>Why is it so?</p>

<p>2 sample outputs:</p>

<blockquote>
  <p>this is main </p>
  
  <p>string1</p>
  
  <p>Process finished with exit code 1</p>
</blockquote>

<p>============</p>

<blockquote>
  <p>string1</p>
  
  <p>this is main</p>
  
  <p>Process finished with exit code 1</p>
</blockquote>

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

<p>From the documentation of <a href="https://docs.python.org/2/library/sys.html?highlight=sys%20exit#sys.exit" rel="nofollow">sys.exit</a>:</p>

<blockquote>
  <p>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.</p>
</blockquote>

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

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

python