Argutus
Argutus

Reputation: 11

Wait for directory (Windows) to exist to continue code? (2.7)

I am trying to have my code detect when a flashdrive is plugged in and then continue the code. I am currently using "os.path.exists". When I start the code with the flashdrive plugged in, the code functions fine, however, if I start when the flashdrive is unplugged, and attempt to plug it in while the code is running, the code never checks to see if the flashdrive is plugged in and keeps forcing the code to sleep. How can I get the code to work?

import os
import sys
import datetime
from datetime import datetime
import shutil
import time

#Wait for FlashDrive to be connected

if os.path.exists("F:\"):
    connected = 1
else:
    connected = 0

while connected == 0:
    print "..."
    time.sleep(10)

#Get current date
currentdate=datetime.now().strftime("%m-%d-%Y")
print "Photos saved: " + currentdate

#Copy and rename DCIM
src = "F:/Pictures"
dst = "C:/Users/Josh/Desktop/photos/" + currentdate
shutil.copytree(src, dst)

The code is supposed to be a loop and execute every time an iPhone connects and never stop running, but I cannot get the code to work if it does not really check for the flashdrive.

Upvotes: 0

Views: 159

Answers (2)

Murph
Murph

Reputation: 1509

Your problem is htat you set the connected variable outside the loop so it's never updated.

Try:

while not os.path.exists('F:\'):
    print("...")
    time.sleep(10)

--edit---

Then, wait for it to be removed at the end:

while os.path.exists('F:\'):
    print("...")
    time.sleep(10)

And, finally, wrap the entire thing in a big while True: so that the whole program repeats.

(Again, I do agree this is a 'hackish' and inefficent way to do this task)

Upvotes: 2

polkovnikov.ph
polkovnikov.ph

Reputation: 6632

Cycle with some arbitrary sleeps isn't a good idea (at all). It makes your program less responsive to the event, because it will take at least N ms to catch an event fired at the start of the iteration*. Also it wastes CPU due to a large amount of API calls.

  1. Create a window.
  2. Listen to WM_DEVICECHANGE message in your message loop. It will fire every time your device configuration changed, but won't tell you, how.
  3. On such event, ask for current configuration.

You can find a tutorial here. Also, take a look at the similar answer on SO.

(*) Actually sleep will test on each next system tick if time_passed >= sleep_timeout. If so, it will return to the program. Problem is that system tick could be 1/18 of second on an old PC (56 ms), so you'll never have 10 ms delay.

Upvotes: 2

Related Questions