Reputation: 105
I'm working on a Python script that goes into a given directory and deletes files based on modification date. I've gotten most of it to work (surprisingly!), except I found a bug. Let me give you all some insight into how my program works.
So, if the user requests that the program runs quietly, I have all of the stdout and stderr information being redirected to a temp text file in a temp folder. Works just fine. There is also an option to run the script continuously. I used a simple while(True) loop to accomplish this. Running continuously worked all fine and dandy, until I wanted to delete that temporary folder after each loop. Here is the code in my main function:
while(True):
display()
verifyDirectory()
checkArgs()
# Deleting the temporary folder after each loop:
if args.q:
deleteTempFolder()
Again, everything worked fine until I tried deleting the temp folder after each loop. The program basically stops after the first loop is completed. Here is the code under the deleteTempFolder():
# Closing the redirected text files.
sys.stdout.close()
sys.stderr.close()
# Defining the paths for the temp folder and the existing text files.
folder = args.directory + "\\" + "temp"
stdoutPath = folder + "\\" + "stdout.txt"
stderrPath = folder + "\\" + "stderr.txt"
# Deleting the text files first, then deleting the entire temporary folder.
os.remove(stdoutPath)
os.remove(stderrPath)
os.rmdir(folder)
I should also note that all of the above code works fine on its own, but when I combined the two (run continuously and delete the temporary folder), that's when I noticed that I break out of my loop.
Also, no errors or exceptions are being generated. I was able to check the stderr file by redirecting it to another location, so it wouldn't be deleted when I ran the code.
I hope all of this makes sense. This is the first time I've asked a question on here, and this is the first script I've ever written that wasn't a silly video game in Java for a course. I'm hoping to post the entire script later for advice on efficiency!
Upvotes: 3
Views: 1948
Reputation: 105
I figured out the solution to my problem, thanks to all of the feedback here. It turns out that I my program was generating errors, but I was unable to see until I commented out sys.stderr.close(). Once I could see where and when the program was crashing, I figured out that I was never recreating the temp folder in my loop, which is slightly embarrassing! Thanks for all the feedback!
Upvotes: 1
Reputation: 2337
There is probably an exception being thrown but not displayed because the error stream is closed. Try this code (python boom.py
) and comment out the sys.stderr.close()
line:
import sys
print("Hello, world")
# this will prevent displaying the exception
sys.stderr.close()
# NameError: name 'nosuchfunction' is not defined
nosuchfunction
print("Goodbye, world")
Upvotes: 2