On Mar 13, 6:21 pm, Carl Banks <[EMAIL PROTECTED]> wrote: > On Mar 13, 7:02 am, Bruno Desthuilliers <bruno. > > > > [EMAIL PROTECTED]> wrote: > > Alex a écrit : > > (sni) > > > > First of all thanks all for answering! > > > > I have some environment check and setup in the beginning of the code. > > > I would like to move it to the end of the script. > > > Why ? (if I may ask...) >
Sure, because of a readability (similar to function declarations in C). > > > But I want it to > > > execute first, so the script will exit if the environment is not > > > configured properly. > > > If you want some code to execute first when the script/module is loaded, > > then keep this code where it belongs : at the beginning of the script. > > I concur with Bruno's recommendation: stuff you want to do first > should come first in the script. Things like BEGIN blocks hurt > readability because you can't identify where execution begins without > reading the whole file. > > Having said that, one thing that often happens in Python scripts is > that all the functions are defined first, then the script logic > follows. So you could put the meat of your script in a function, then > the "BEGIN" stuff after that functions: > > def run_script(): > # > # script contained in this long function > # > > # Then test preconditions here... > if os.environ["HELLO"] != "WORLD": > sys.exit(2) > > # Then call the run_script functions > run_script() > > But having said THAT, I don't recommend you do that with > preconditions. If the script has a quick early exit scenario, you > really ought to put that near the top, before the function > definitions, to clearly show to a human reader what is necessary to > run the script. > > Carl Banks Hi, Maybe i was a little bit unclear... I meant that i wanted to do something like this: #!usr/bin/env python check_env() from subprocess import * class MyClass: # Class definition def check_env(): # Code if __name__ == "__main__": # Script logic The thing is, as i saw, that Python doesn't recognize the "check_env()" function before it reaches the "def" statement. I need the check to be done before the subprocess import, because our customers use different Python versions, some of them do not have subprocess module. So i want to exit if i see that Python version being used doesn't have that module. The solution to that problem with what you suggested could be wrapping the subprocess import with function, am i correct? -- http://mail.python.org/mailman/listinfo/python-list