I am using the below python code to run multiple python files in a directory D:\PYTHON FILES
using try except method. I need to print the name of the file that has failed to run.Please refer the codes below. Could anyone help me in view of this?
Please Note:
Please run this in DOS prompt and do not use IPython
. Place all your python files including one corrupt file in the directory D:\PYTHON FILES
import os, glob
dir='D:\PYTHON_FILES'
os.chdir(dir)
files = glob.glob ('*.py');
for eachfile in files:
try:
os.system('python '+eachfile+'\n')
except:
print(eachfile + ' missed out')
finally:
print('======================')
The mentioned code requires some corrections, for example
import os, glob
dir_path = 'D:\PYTHON_FILES'
os.chdir(dir_path)
file_names = glob.glob('*.py')
for file_name in file_names:
return_value = os.system('python {}'.format(file_name))
if return_value != 0:
print('{} missed out'.format(file_name))
print('=' * 24)
for more pythonic solution. The non-zero return value signs that there was some problems with the execution of the command of system
function.