1
votes

I'm trying to determine if a directory exists on a shared network drive.

import os

if(os.path.exists('/Volumes')):
 print 'path exists'
else:
 print 'path does not exist'

This works fine but this fails when passing in this argument: '/Volumes/A21\ 's\ Public\ Folder'

This makes sense to me because this does not exist until I open up the shared drive on Finder. So I guess I need to mount first, which I've tried from the command line first -

mount_smbfs smb://guest@server/A21's Public Folder

This fails, so I'm unsure of what to pass in for the os.path.exists argument. Ideally, I want to be able to mount into /Volumes/A21's Public Folder first, and then later check if that folder exists?

2
What exactly are you mounting it to? It appears you're not mounting it at all... you need a mount point.l'L'l
That's correct, I was not mounting earlier. So I have added this line before the if statement - os.system("osascript -e 'mount volume \"smb://A21._smb._tcp.local/A21\'s\ Public\ Folder\"'") but it's failing due to incorrect quote markup. I presume this would enable the folder to be accessed under /Volumes?A21
You can put it under /Volumes, although I prefer the users home directory because you know it has the proper permissions; you could always make a symlink from /Volumes to ~/mnt also I suppose...l'L'l

2 Answers

1
votes

In Python you would do basically the same routine as you would in Bash mounting shares:

#!/usr/bin/python

import os

home = os.path.expanduser("~")
mnt = home + "/mnt"

if not os.path.exists(mnt): os.makedirs(mnt)
os.chdir(mnt)

os.system("mount_smbfs //username@server._smb._tcp.local/share " + mnt)

What this does is sets the mount point to mnt in the users home directory; if the folder doesn't exist then it creates it. Then the command changes into that directory and mounts thesmb. You'll need to enter your password, or if you want to have a really non-secure way, then you can always include the password in the command (eg. username:password).

Once your share is mounted you can check if the file exists with:

os.path.exists(mnt + "/path/to/file")
0
votes

The problem might be that your copying and pasting the string. I've had problems with this before. When dealing with file paths it's best to use os join you encounter less problems

Try using:

os.path.join

for example:

import os

pathtodrive = os.path.join("Volumes", "A21's Public Folder")

if (os.path.exists(pathtodrive)):
    print 'path exists'
else:
    print 'path does not exist'