Memo‎ > ‎

My memo on python

posted May 17, 2014, 8:56 AM by Teng-Yok Lee   [ updated May 27, 2014, 1:22 AM ]

My tricks

Write a script that can be imported

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;

Then I will check whether this script is directly called by python. If yes, immediately call main():

# Entry point of the script.
import os;
import sys;
...
if( os.path.basename(sys.argv[0]) == os.path.basename(__file__) ):
    exit(main(sys.argv));

To call this script from another script (says my_script), now just called its main():

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__.


Comments