繁体   English   中英

Python,逐步浏览文件夹(运行脚本)

[英]Python, step through folders (to run scripts)

由于我不熟悉Python,所以我想来这里。

无论如何,我有几个文件夹(让我们说20个文件夹),每个文件夹中有更多文件夹(让每个人说5个文件夹),并且在每个文件夹中,其中一个文件夹是另一个文件夹,而在该文件夹中,我需要运行一个脚本。

脚本的运行方式与'ie':sh script.sh相同

基本上,我需要为每个文件夹运行该脚本,问题是我不知道如何进入每个文件夹(具有脚本),该文件夹比原始文件夹低4级。

因此,总共有大约120个脚本需要以相同的方式运行(例如,该脚本还返回一个数字)(我需要记录一个数字(1表示成功,0表示失败))(应该很难找出来) )

最好的方法是什么? 我认为我可以弄清楚Checking的结果,但是逐步浏览所有这些子文件夹我实在不太了解python。

 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) 

不要问我为什么文件夹是这样构造的.....大声笑。 最好在python 2中完成。

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

有点矫kill过正,但应该可以:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM