Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Refresh Network Drive Mappings in Python

Tags:

python

windows

I have a drive already mapped to a designated letter, 'R:\'. If I run the python script to access this space while logged on or with the computer unlocked it works fine. The problem occurs when I set task scheduler to run the script early in the morning before I come in. Basically I stay logged in and lock the machine, but at some point it looks like my network drive mappings time out (but reconnect when I unlock the machine in the morning) and this is why the script isn't able to find them.

The error comes when trying to do an os.path.exists() to check for folders on this drive and create them if they don't already exist. From a 'try/except' loop I get the exception "The system cannot find the path specified: 'R:\'.

My question: is there a way to force a refresh through python? I have seen other postings about mapping network drives...but not sure if this applies to my case since I already have the drive mapped. The letter it uses needs to stay the same as different applications have absolute references to it. Wondering if mapping the same drive will cause problems or not work, but also not wanting to temporarily map to another letter with a script and unmap when done...seems like an inefficient way to do this?

Using python 2.6 (what another program requires).

Thanks,

like image 729
user1229108 Avatar asked Nov 13 '22 07:11

user1229108


1 Answers

The best solution would be to refer to the 'drive' by its UNC pathname, i.e. a path of the form \\hostname\sharename, but, unfortunately, Python's base library has very poor support for dealing with UNC paths.

Option #1 would be to find a Python extension module you can install to get better support for UNC paths. Try googling for "python unc".

Option #2 would be to use the Python subprocess module to execute net use commands, and parse the resulting output. e.g. from a DOS prompt, running net use will output something like this...

Status       Local     Remote                    Network
-------------------------------------------------------------------------------
OK           R:        \\hostname\sharename      Microsoft Windows Network

...which you can use to tell if the drive is already mapped, and if not, you can just execute net use R: \\hostname\sharename to map it. It's possible that calling net use with no paramaters is actually sufficient to 'refresh' the mapping if it has 'timed out', but I'm not sure.

Option #3 would be to investigate using the Python ctypes module to call the underlying Windows libraries directly to emulate the functionality of calling net use.

like image 126
Aya Avatar answered Nov 14 '22 21:11

Aya