pepitooo
9/30/2016 - 12:00 PM

Run same command in all directories, usefull when you want to do a "git pull" $ python run_in_directories.py -f tirs* -c "git pull"

Run same command in all directories, usefull when you want to do a "git pull" $ python run_in_directories.py -f tirs* -c "git pull"

#! python
import argparse
import os
import sys
import logging
from subprocess import Popen, PIPE

def parse_args(args):
    """
    Parse command line parameters

    :param args: command line parameters as list of strings
    :return: command line parameters as :obj:`airgparse.Namespace`
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
            '-f', '--folder',
            nargs='*',
            dest='folder',
            help='folders to run command',
            default=argparse.SUPPRESS)
    parser.add_argument(
            '-c', '--command',
            dest='command',
            help='command line as a string "ls -s al"',
            default=argparse.SUPPRESS)
    return parser.parse_args(args)


def main(args):
    args = parse_args(args)
    folders = args.folder
    command = args.command
    for folder in folders:
        origWD = os.getcwd() # remember our original working directory
        path = os.path.join(os.path.abspath(sys.path[0]), folder)
        os.chdir(path)
        print('command "{}" will be run in folder: {}'.format(command, path))
        print(Popen(
            command, 
            shell=True, 
            stdout=PIPE
        ).stdout.read().decode('ascii'))
        os.chdir(origWD)


def run():
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    main(sys.argv[1:])


if __name__ == '__main__':
    run()