Created
September 30, 2011 08:00
-
-
Save fiee/1253034 to your computer and use it in GitHub Desktop.
file system helpers (part of an old toolbox)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
:Author: Henning Hraban Ramm | |
:Organization: fiëé virtuëlle, www.fiee.net | |
:Contact: mailto:hraban@fiee.net | |
:Version: 0.3.6 | |
:Date: 2006-01-24 | |
:Status: beta | |
:License: same as Python | |
:Abstract: file system helpers for Windows, with twisted | |
imports plainfs into own namespace | |
Changelog | |
========= | |
========== ======= =========================================================== | |
date version changes | |
========== ======= =========================================================== | |
2006-01-24 0.3.6 changed author information and some doc strings | |
2005-11-09 0.3.5 alle Pfade mit / statt \ | |
2005-09-26 0.3.4 ? | |
========== ======= =========================================================== | |
""" | |
__docformat__ = "restructuredtext en" | |
__version__ = "0.3.6" | |
from twisted.internet import threads | |
import os.path, shutil | |
import win32api, win32net | |
from plainfs import * | |
def copy(source, target, overwrite=False): | |
""" | |
Copy file in separate thread. | |
Return a deferred Boolean, if the file could be copied. | |
If the target file exists, the source is only copied if overwrite=True. | |
""" | |
d = threads.deferToThread(_doCopy, source, target, overwrite) | |
return d | |
def _doCopy(source, target, overwrite): | |
source=fixpath(source) | |
target=fixpath(target) | |
sourcedir, sourcefile = os.path.split(source) | |
if isDir(target): | |
targetfile = sourcefile | |
targetdir = target | |
else: | |
targetdir, targetfile = os.path.split(target) | |
ensuredir(targetdir) | |
targetfile = fixpath(os.path.join(targetdir, targetfile)) | |
if overwrite or not os.path.exists(targetfile): | |
#print "Copy %s to %s" % (source, targetfile) | |
shutil.copy(source, targetfile) | |
return os.path.exists(targetfile) | |
else: | |
return False | |
def move(source, target, overwrite=False): | |
""" | |
Move file in separate thread. | |
Return a deferred Boolean, if the file could be moved. | |
If the target file exists, the source is only moved if overwrite is True. | |
""" | |
d = threads.deferToThread(_doMove, source, target, overwrite) | |
return d | |
def _doMove(source, target, overwrite): | |
targetdir, targetfile = os.path.split(target) | |
sourcedir, sourcefile = os.path.split(source) | |
ensuredir(targetdir) | |
if not targetfile: | |
targetfile = sourcefile | |
targetfile = os.path.join(targetdir, targetfile) | |
if not os.path.exists(targetfile) or overwrite: | |
source = fixpath(source) | |
targetfile = fixpath(targetfile) | |
shutil.move(source, targetfile) | |
if os.path.exists(targetfile): | |
if os.path.exists(source): | |
os.unlink(source) | |
return True | |
return False | |
ByteUnit = { | |
'B' : 1024**0, | |
'kB' : 1024**1, | |
'MB' : 1024**2, | |
'GB' : 1024**3, | |
'TB' : 1024**4 | |
} | |
def getFreeDiskSpace(disk, mode='MB'): | |
""" | |
Return the amount of available space on a disk (e.g. 'C:'). | |
Modes: see ByteUnit (B, kB, MB, GB, TB) plus % | |
""" | |
(freebytes, totalbytes, totalfreebytes) = win32api.GetDiskFreeSpaceEx(disk) | |
if mode in ByteUnit: | |
return float(freebytes) / ByteUnit[mode] | |
else: | |
return float(freebytes) * 100 / float(totalbytes) | |
def getLocalDrives(): | |
return win32net.NetServerDiskEnum('', 0) | |
def getDrives(): | |
""" | |
return a dict of drive letter to remote share | |
""" | |
res = win32net.NetUseEnum('', 0) | |
drives = res[0] | |
while res[2]: | |
res = win32net.NetUseEnum('', 0) | |
drives.extend(res[0]) | |
# drives ist jetzt eine Liste von dicts, jeweils mit den keys remote und local | |
myname = os.environ['COMPUTERNAME'].lower() | |
ddict = dict([ (en['local'].upper(), en['remote']) for en in drives ]) | |
ddict.update(dict([ (d, '//%s/%s$' % (myname, d[0])) for d in getLocalDrives()])) | |
return ddict | |
def getNetPath(path): | |
""" | |
expand a drive letter to a network share, if possible | |
""" | |
drive, path = os.path.splitdrive(fixpath(path)) | |
if drive: | |
path = path.strip('/') | |
drive = drive.upper() | |
ddict = getDrives() | |
if drive in ddict: | |
return os.path.join(ddict[drive], path) | |
return path | |
def getComputerName(path): | |
""" | |
on which computer is that path? | |
""" | |
path = fixpath(path) | |
if not path.startswith('//'): | |
path = getNetPath(path) | |
path = path.split('/')[2] | |
return path.replace('/','') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
:Author: Henning Hraban Ramm | |
:Organization: fiëé virtuëlle, www.fiee.net | |
:Contact: mailto:hraban@fiee.net | |
:Version: 0.4.1 | |
:Date: 2006-01-24 | |
:Status: beta | |
:License: same as Python | |
:Abstract: file system helpers, OS independent and without twisted | |
Changelog | |
========= | |
========== ======= =========================================================== | |
date version changes | |
========== ======= =========================================================== | |
2006-01-24 0.4.1 changed author information and some doc strings, | |
removed some too specialized functions and dependencies | |
2005-12-14 0.4.0 new: FileNumber, byFileNumber, byZipFileNumber | |
2005-11-09 0.3.7 fixpath: change for UNC paths, only / instead of \ | |
2005-10-20 0.3.6 ? | |
========== ======= =========================================================== | |
""" | |
__docformat__ = "restructuredtext en" | |
__version__ = "0.4.1" | |
import os, os.path, re | |
ABSPATH = re.compile('^([A-Z]:)?[\\/]+.*', re.I) | |
# absolute path, starts with drive letter or UNC server name (Windows only) | |
def fixpath(path): | |
""" | |
try to make an absolute path from 'path' and replace all delimiters with '/' | |
""" | |
path = os.path.abspath(path) | |
path = path.replace(chr(92), '/') # UNC works only with //, not with \\ | |
return path | |
def basefilename(path): | |
""" | |
return the basic filename without path and extension | |
""" | |
(path, filename) = os.path.split(path) | |
(filename, ext) = os.path.splitext(filename) | |
return filename | |
def ensuredir(dir): | |
""" | |
Create directory tree if needed. | |
""" | |
if not dir: return False | |
dir = fixpath(dir) | |
if isDir(dir): return True | |
try: | |
os.makedirs(dir) | |
# makedirs doesn't work on SMB shares etc. | |
# makedirs funktioniert z.B. nicht auf SMB-Shares | |
except OSError: | |
rest, letzter = os.path.split(dir) | |
if not (isDir(rest)): | |
ensuredir(rest) | |
else: | |
try: | |
os.mkdir(dir) | |
except OSError, ex: | |
# otherwise only "invalid argument" | |
raise OSError(ex, dir) | |
return True | |
def checkdir(dirname, basedir=None): | |
""" | |
Check if a directory exists, return approved dirname (or None). | |
dirname : absolute or relative directory name | |
basedir : base for relative directory names | |
""" | |
if not ABSPATH.match(dirname): # relatives Verzeichnis | |
dirname = os.path.join(basedir, dirname) | |
if not isDir(dirname): | |
#raise IOError('%s is no directory' % dirname) | |
dirname = None | |
return dirname | |
def isDir(path): | |
""" | |
Is path a directory or mount (share)? | |
""" | |
return os.path.isdir(path) or os.path.ismount(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment