2

I experienced the following issue when using the Audacity scripting environment for python. It creates a temporary file where one can write commands that are to be executed by Audacity. The two relevant files are being create upon Audacity launch.

My script contains the following snippet (original source):

# Initialize variable depending on os:
if sys.platform == 'win32':
    print("pipe-test.py, running on windows")
    TONAME = '\\\\.\\pipe\\ToSrvPipe'
    FROMNAME = '\\\\.\\pipe\\FromSrvPipe'

# Check if temp files actually exist
if not os.path.exists(TONAME):
    print(" ..does not exist.  Ensure Audacity is running with mod-script-pipe.")
    sys.exit()

Everything fine so far, the file is found. Then I tried to open it, and the operation failed every time. I did some tweaking here and there, but eventually found this strange behavior indicating that opening the file was not the problem, but the exists() check. I changed my code like this:

# Initialize variable depending on os:
[...]

# Check if temp files actually exist (it exists)
if not os.path.exists(TONAME):
    print(" ..does not exist.  Ensure Audacity is running with mod-script-pipe.")
    sys.exit()

# Check if temp files actually exist (it is gone)
if not os.path.exists(TONAME):
    print("File is gone now")
    sys.exit()

The second check would tell me that the file suddenly disappeared after I just checked for its existence. How is this possible? How is it possible that os.path.exists() deleted my temporary file?

PKlumpp
  • 4,913
  • 8
  • 36
  • 64
  • 2
    *"# Check if temp files actually exist"* - Don't do that. This applies to file system interactions in general. Open the file, if that fails with an "does not exist" error, that's when you know that file does not exist. You have to write that error handler anyway, which means that "exists" checks are fundamentally superfluous. – Tomalak May 26 '20 at 14:29
  • 2
    What @Tomalak said is often referred to as the [EAFP principle](https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python) (Easier to Ask Forgiveness than Permission). – Jonathon Reinhart May 26 '20 at 14:31
  • Thanks, I will give this a try. As you can see from the provided source, this is a sample code, and I assume it worked on other machines so far. I didn't know it was bad practise in general. – PKlumpp May 26 '20 at 14:31
  • Filesystems are weird places. A million things happen on them in concurrent threads over many processes, most of which you have no control over. There is no telling if a fact you have established in the previous line of your code still is true when the next line executes a millisecond later. Your `exists()` check may succeed but your `open()` may still fail. But the result of the `open()` call the useful thing, the `exists()` call is just fluff. Writing it "to make sure the `open()` won't fail" cannot work. – Tomalak May 26 '20 at 14:36

0 Answers0