0

I'm quite new to python and I need some advice.

This how I organized and wrote my script:

#!/usr/bin/python

import ...

exitCode = 1   

def sendmail(mess,type): 
    [...]
    if ...
       exitCode = 9
    else
       exitCode = 1

    [...]
    return 0

#=====
#start

[...]

try:
    [...]

except:  
    sendmail(message,"connect")
    sys.exit(exitCode)

sys.exit(0)
  1. import part
  2. variables definition
  3. function sendmail
  4. start (should be my main) which contains some sets of try/except and if/else

I would like to understand a couple of things:

  1. Did I structured my script in the correct way? I did not understand how is the main function defined, sometimes it is used, sometimes not... what should be the best to do?

  2. In the "main" at a certain point sendmail function is called, which, if something goes wrong, sets the variable exitCode to 9. Than further processing is done and it returns 0. Now exitCode is defined at the very top so I expect to be a global variable. But if I read it's value in the except (soon after the sendmail) it's value is "1" while I expect a "9". if I read it in the sendmail function the value is correctly "9". What am I doing wrong? I think I could use return exitCode instead of return 0, but I would like to understand the mistake.

ElGavilan
  • 6,610
  • 16
  • 27
  • 36
d82k
  • 379
  • 7
  • 17
  • [Python Scopes and Namespaces](https://docs.python.org/2.7/tutorial/classes.html#python-scopes-and-namespaces). [Naming and Binding](https://docs.python.org/2.7/reference/executionmodel.html#naming-and-binding) – wwii Jan 20 '15 at 14:40

2 Answers2

1

There are two different exitCodes in your code. The one in the global scope, which you assign just after import; and the one inside sendmail. Modifying one will have no effect on the other. If you want to modify the global exitCode from within the function, use the global statement.

def sendmail(mess,type): 
    global exitCode
    [...]
Kevin
  • 74,910
  • 12
  • 133
  • 166
1
  1. The best thing is to use

    if __name__ == "__main__":
    

as a main entry point to your code (see explanation here).

  1. To address a variable on the global scope, you should precede it with:

    global exitCode
    

However, using global variables is generally discouraged. In your case, it may be better to set the return value of the sendmail() function to be the exit code, so it will look like this:

#!/usr/bin/python

import ...

def sendmail(mess,type): 
    [...]
    if ...
       exitCode = 9
    else
       exitCode = 1

    [...]
    return exitCode

#=====
#start

[...]

try:
    [...]

except:  
    exitCode = sendmail(message,"connect")
    sys.exit(exitCode)

sys.exit(0)        
Community
  • 1
  • 1
urim
  • 591
  • 4
  • 13
  • Thank you, I will modify the code accordingly and try! Thank you also for the link! – d82k Jan 20 '15 at 15:56