Script only works once, although I use "while (True)"
I am working on a Python script that goes into a given directory and deletes files based on modified date. I got most of the work (amazing!) Except that I found a bug. Let me give you some idea of how my program works.
So, if the user asks that the program runs quietly, I have all the stdout and stderr information redirected to a temporary text file in the temp folder. Works great. There is also the option to run the script continuously. For this I used a simple loop (True). Work continuously worked fine and dandy until I wanted to delete this temp folder after every cycle. 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 to delete the temp folder after each cycle. The program basically stops after completing the first cycle. Here is the code under 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 point out that all of the above code works fine on its own, but when I merged the two (run continuously and delete the temp folder), that's when I noticed that I was exiting my loop.
Also, no errors or exceptions are thrown. I was able to check the stderr file by redirecting it to a different location so it won't get deleted when I run the code.
Hope this all makes sense. This is the first time I have asked a question here and this is the first script I have ever written, it was not a silly Java video game for a course. I hope to post the entire script later for efficiency tips!
source to share
The exception is probably being thrown but not displayed because the error stream is closed. Try this code ( python boom.py
) and comment out the line sys.stderr.close()
:
import sys
print("Hello, world")
# this will prevent displaying the exception
sys.stderr.close()
# NameError: name 'nosuchfunction' is not defined
nosuchfunction
print("Goodbye, world")
source to share
I figured out a solution to my problem thanks to all the reviews here. It turns out that my program was generating errors, but I couldn't see until I commented out sys.stderr.close (). As soon as I saw where and when the program crashed, I realized that I had never recreated the temp folder in my loop, which is a little awkward! Thanks everyone for the feedback!
source to share