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.

1

2 Answers 2

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)        
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I will modify the code accordingly and try! Thank you also for the link!
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
    [...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.