Accessing a Windows shared drive on a remote server in Python

Stuart picture Stuart · Oct 4, 2012 · Viewed 11.2k times · Source

This seems like a simple problem, but I'm having trouble figuring it out.

I set up a shared folder on a remote server so that the folder shows up in the Windows Explorer as follows: \\server-name\shared-directory. I am able to read from that folder remotely and write to that folder remotely via the Windows Explorer. When I try to access that file via a python script, however, I it says the directory does not exist.

I have administrative rights to the server and gave myself access to the shared drive (I verified this by copying files via Windows Explorer).

In python, I am accessing the drive as follows (although I tried several different ways and had no success):

os.access('\\\\server-name\\path-to-shared-directory', os.W_OK)

Any suggestions on what I might be doing wrong?

EDIT:

In response to questions, I am actually trying to copy files using the script, os.access was just used to see if the directory had write access. The copy code I am using is as follows:

def copy_folder(src, dest):
    if not os.access(dest, os.W_OK):
        return(False)
    cmd = ['xcopy', '/E', '/J', '/Y', '/I', src, dest]

    p = subprocess.Popen(args=cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    out, err = p.communicate()

    print 'out: %s' % out
    print 'err: %s' % err

    return(True)

copy_folder(my_source_directory, '\\\\server-name\\path-to-shared-directory')

This returns 'Invalid drive specification' as an error.

Answer

jdi picture jdi · Oct 4, 2012

You should have no problem accessing files via the UNC path that you are already attempting to use, but I would recommend formatting it a bit differently to help with escaping:

src  = r'C:\path\to\source'
dest = r'\\server-name\path-to-shared-directory'

And you don't need stdin:

p = subprocess.Popen(cmd, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE, 
        shell=True)

Normally you would be able to use forward slashes for paths in python, but since you are calling out to a shell command, the backslashes are still needed.