'Running a script inside a try except clause
I am semi-new to Python and am confused about a try except clause I am trying to execute. I currently have a list of R scripts and want a master Python script to execute each R script. I want the Python script to attempt to run the R script and if the R script cannot find the file it is looking for, I want the Python script to return a matrix of which scripts could not find the files.
I currently have this code:
import os
import glob
import subprocess
os.chdir('C:/Users/Brandon/scripts')
listOfScripts = glob.glob('*.R')
height = len(listOfScripts)
width = 2
errorMatrix = [[0 for x in range(width)] for y in range(height)]
for script in listOfScripts:
try:
subprocess.call (["C:/Program Files/R/R-4.1.2/bin/Rscript", "--vanilla", script])
scriptThatSucceeded = listOfScripts.index(script)
errorMatrix[scriptThatSucceeded][0] = script
errorMatrix[scriptThatSucceeded][1] = "passed"
except:
scriptThatFailed = listOfScripts.index(script)
errorMatrix[scriptThatFailed][0] = script
errorMatrix[scriptThatFailed][1] = "File not found"
print(errorMatrix)
This works completely fine if there are files to be found (I can easily manipulate the source R script to purposefully attempt to find a non-existent file for checking), and I get the output:
[['055.R', 'passed'], ['282.R', 'passed'], ['283.R', 'passed'], ['346.R', 'passed']], which is what I am expecting. When I change one script, to search for a file that doesn't exist, I get this message in the Python terminal:
Error in file(file, "rt") : invalid 'description' argument
Calls: ingestion -> read_new_data -> read.csv -> read.table -> file
Execution halted
[['055.R', 'passed'], ['282.R', 'passed'], ['283.R', 'passed'], ['346.R', 'passed']]
The terminal displays the error message from the R script first, then continues on printing the error matrix as if every script had passed, even though the last script should have failed. Can someone help me?
Solution 1:[1]
If the except block is triggered, the code will continue executing after leaving the except block. except blocks are used for error / exception handling.
If you want to halt the execution of the Python script if there is an issue with the R script, either remove the except block or reraise the exception.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
