I usually write python scripts for small task. Scripts can be executed quickly (without setting program variables), but they are hard to debug when scripts are calling scripts. In such a case, the ability to run scripts like a module will be better. Here is my template to write a python script so it can be also called as a module. In each script, I just define a method main(), which define the main computation. from optparse import OptionParser; # Define the parser. parser = OptionParser() ... def main(arguments): (options, args) = parser.parse_args(arguments) ... return 0; # Entry point of the script. import os; import sys; ... if( os.path.basename(sys.argv[0]) == os.path.basename(__file__) ): exit(main(sys.argv)); import my_script; ... # Setup the argument. arguments = [ ...]; my_script.main(arguments) ; Useful links about advanced python usage:How to get the python.exe location programmatically?import sys; ... python_exec = sys.executable; Usage: On Windows, I use WinPython + Eclipse for developing. If I want to call another python scripts, I need to pass the correct python interpreter. Otherwise, the default python might not have the packages I needed (such as numpy). In Python, how do I get the path and name of the file that is currently executing? Use the keyword __file__. |
Memo >