Im writing a program to walk a filesystem using os.walk.
I have my for loop using os.walk, and onerror function as follows:
def walk_error(os_error):
return(os_error)
def main():
for root, dirs, files in os.walk('/var/spool/cron/', onerror=walk_error):
print(root, dirs, files)
Where does that return statement from the onerror function go to? How do I reference it? I can certainly just do print(os_error) in my walk_error function and it will work fine.
But I want to save that error somewhere.
How do I, say, add a list as an argument to the error handling function aswell, so I can append that error to a list of my failed directories?
For example:
def walk_error(os_error, list_of_errors):
list_of_errors.append(os_error)
That would work great! But unfortunately it doesnt seem you can do that type of a function call with multiple arguments in the onerror call.
Or how do I assign that returned value to a variable to do that in my main function? That os_error is being "returned" but its not returned to any of the 3 tuples that os.walk generates. Is there a way to reference that returned value in main()?
How do I do more complicated error handling here?
Use an inner function (aka closure):
def main():
list_of_errors = []
def walk_error(os_error):
list_of_errors.append(os_error)
for root, dirs, files in os.walk('/var/spool/cron/', onerror=walk_error):
print(root, dirs, files)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With