2010-06-22 101 views

回答

13

是的,它可以做到。首先,從Python中調用這樣的命令mount你的SMB網絡共享到本地文件系統:

mount -t smbfs //[email protected]/sharename share 

(您可以使用subprocess模塊做到這一點)。 share是SMB網絡共享將被加載到的目錄的名稱,我猜它必須是用戶可寫的。之後,您可以使用shutil.copyfile複製文件。最後,你要卸載這個SMB網絡共享:

umount share 

也許這是最好的在Python中創建一個上下文管理器,需要安裝和卸載的護理:

from contextlib import contextmanager 
import os 
import shutil 
import subprocess 

@contextmanager 
def mounted(remote_dir, local_dir): 
    local_dir = os.path.abspath(local_dir) 
    retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir]) 
    if retcode != 0: 
     raise OSError("mount operation failed") 
    try: 
     yield 
    finally: 
     retcode = subprocess.call(["/sbin/umount", local_dir]) 
     if retcode != 0: 
      raise OSError("umount operation failed") 

with mounted(remote_dir, local_dir): 
    shutil.copy(file_to_be_copied, local_dir) 

上面的代碼片斷沒有經過測試,但它應該一般工作(除了語法錯誤,我沒有注意到)。還請注意,mounted與我在其他答案中發佈的network_share_auth環境管理器非常相似,因此您可以通過檢查使用platform模塊的什麼平臺,然後調用相應的命令來將兩者結合起來。

+0

酷!得到它的工作!感謝您的快速(和精心製作的)回覆! (想投票,但沒有足夠的代表: - |) – Gumbah 2010-06-22 10:41:17

相關問題