I've got a Python script which is meant to launch several other shell scripts with the appropriate setup and parameters. I construct the file paths from other variables so that it's easier to change one setting and have it apply everywhere, rather than hardcoding everything. So, for example:
HOME_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
ONHAND_ACC_NAME = 'onhand_accuracy'
SHRINK_NAME = 'shrink'
SHELL_SCRIPT_EXTENSION = '.ksh'
CONFIG_FILE_EXTENSION = '.conf'
ONHAND_ACC_SHELL_SCRIPT = HOME_DIRECTORY + '/' + ONHAND_ACC_NAME + SHELL_SCRIPT_EXTENSION
SHRINK_SHELL_SCRIPT = HOME_DIRECTORY + '/' + SHRINK_NAME + SHELL_SCRIPT_EXTENSION
ONHAND_ACC_CONFIG_FILE = HOME_DIRECTORY + '/' + ONHAND_ACC_NAME + CONFIG_FILE_EXTENSION
SHRINK_CONFIG_FILE = HOME_DIRECTORY + '/' + SHRINK_NAME + CONFIG_FILE_EXTENSION
These are all constants defined at the top of the script. (Feel free to tell me a more Pythonic way to do this than constants, as well. I've heard before that "Python should have no constants at all", though I'm not sure how accurate or purist that is.)
In Java, I would do something much cleaner, like use an enum
to generate appropriate file paths as needed:
public enum FileType {
SHELL_SCRIPT (".ksh"),
CONFIGURATION (".conf");
private static final String HOME_DIRECTORY = "/path/to/scripts";
private static final String FILE_SEPARATOR = FileSystems.getDefault().getSeparator();
private final String extension;
private FileType(String extension) {
this.extension = extension;
}
public String getFilePath(String name) {
return HOME_DIRECTORY + FILE_SEPARATOR + name + extension;
}
}
Then I could simply invoke this whenever I wanted to and get a file path, rather than hardcoding them as constants, like so:
FileType.SHELL_SCRIPT.getFilePath("onhand_accuracy");
Any similar tips on how I can improve this practice/technique in Python? I know I could have a similar function in Python that uses a lot of if/elif
on a string
input, but that still seems much dirtier than an enum
, since the calling code can pass in whatever it wants for that string
.
(In the Java, I would probably also have an enum
for the associated Script
, but that would clutter up my example.)