Last active
September 30, 2016 12:06
-
-
Save pepitooo/0e419cc3fbe57cdbd1797b301a330369 to your computer and use it in GitHub Desktop.
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment