user475353
user475353

Reputation:

Python, step through folders (to run scripts)

Since Im unfamiliar with Python I thought i'd come here.

Anyways I have several Folders (lets say 20 folders) Within each folder is more folders (lets say 5 per) and within EACH one of these folders is another folder, and within THAT is a script I need to run.

The script is ran the same way 'ie':sh script.sh

Basically I need to run this script for each of these folders, problem is I have no clue how to step into each folder (that has the script) which is 4 levels down from the original folder.

So there are a total of like 120 scripts that need to be ran the same way (this script also returns a number for instance (1 for success, 0 for failure) that I need to record (shouldn't be too hard to figure out)

What would be the best way to go about this? The Checking results I think I can figure out, but stepping through all these subfolders Im honestly not well versed in python to know about.

Just so everyones clear the folder structure is like this:
Top Level (20 or so folders)
 -->1 Below (5 or so Folders)
 ----->1 below one of these 5 folders (only 1 folder is contained)
 --------->1 below that one folder (here is where the script resides)

Don't ask me why the folders are structured this way.....lol. This would be done in python 2 preferably.

Upvotes: 1

Views: 1034

Answers (2)

phihag
phihag

Reputation: 287775

import glob,subprocess
for script in glob.glob('*/*/*/*.sh'):
   s = subprocess.Popen([script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   stdoutdata,stderrdata = s.communicate()
   returncode = s.returncode
   # Do something with stdoutdata, returncode etc. here

Upvotes: 2

Blender
Blender

Reputation: 298106

A bit overkill, but it should work:

import os

root = '/foo/'

for directory, subdirectories, files in os.walk(root):
  for file in files:
     if os.path.splitext(file)[-1].lower() == '.sh':
       os.system('sh ' + os.path.join(directory, file))

Upvotes: 1

Related Questions