Question

I wrote a script to concatenate a variable called classpath_augment using python. I was able to successfully concatenate directories and the contained jar files to the classpath_augment variable, however, I also need to add to the classpath variable those directories that contain .properties files.

How can I do that?
Below is my code:

#! /usr/bin/env python

import os
import sys
import glob

java_command = "/myappsjava/home/bin/java -classpath "

def run(project_dir, main_class, specific_args):

        classpath_augment = ""

        for r, d, f in os.walk(project_dir):
                for files in f:
                        if (files.endswith(".jar")):
                                classpath_augment += os.path.join(r, files)+":"

        if (classpath_augment[-1] == ":"):
                classpath_augment = classpath_augment[:-1]

        args_passed_in = '%s %s %s %s' % (java_command, classpath_augment, main_class, specific_args)
        print args_passed_in
        #os.system(args_passed_in)
Was it helpful?

Solution

Just look for .properties files:

def run(project_dir, main_class, specific_args):
    classpath = []

    for root, dirs, files in os.walk(project_dir):
        classpath.extend(os.path.join(root, f) for f in files if f.endswith('.jar'))
        if any(f.endswith('.properties') for f in files):
            classpath.append(root)

    classpath_augment = ':'.join(classpath)

    print java_command, classpath_augment, main_class, specific_args

I took the liberty of simplifying your code somewhat; using a list to collect all classpath paths first, then use str.join() to create a final string. This is faster than concatenating each new path one by one.

If you are using a very old Python version and any() is not yet available, use a for loop:

def run(project_dir, main_class, specific_args):
    classpath = []

    for root, dirs, files in os.walk(project_dir):
        has_properties = False
        for f in files:
            if f.endswith('.jar'):
                classpath.append(os.path.join(root, f))
            if f.endswith('.properties'):
                has_properties = True
        if has_properties:
            classpath.append(root)

    classpath_augment = ':'.join(classpath)

    print java_command, classpath_augment, main_class, specific_args
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top