按照常规的理解:一个模块可包含若干个类,类可包含若干个函数,函数由若干个表达式或语句组成。要将python写好,使代码具有高重用性,那么类的封包,是必须要学好的
有时候模块的导入需要一个叫做“路径搜索”的过程。即在文件系统“预定义区域”中查找mymodule.py文件(如果你导入mymodule的话)。这些预定义区域只不过是你的python搜索路径的集合。
>>> import sys>>> sys.path['', '/usr/lib64/python26.zip', '/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old', '/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages', '/usr/lib/python2.6/site-packages', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info']
当提示ImportError: No module named xx时,说明模块不在搜索的路径里,可以通过sys.path.apped(‘/home/jack/xxx’)这样的方法进行添加
解决了环境问题,下面,看一下所写的代码:
[root@www manual]# tree.├── file_backup_run.py├── file_backup_run.pyc├── file_init.py├── file_init.pyc└── file_start.py
有三个文件,file_start是开始文件,里面放了主函数,file_init里面定义了一下类,用来初始化需要备份的文件路径,file_backup_run是运行类,下面我们看一下文件是怎么写的
file_start:
#!/usr/bin/python#coding=utf8#Filename: file_start.pyimport osimport timeimport socketfrom file_init import FileBackupPathfrom file_backup_run import BackupFiledef main(): a = FileBackupPath() a.entersourcepath() a.entertargetpath() sdir = a.getsdir() tdir = a.gettdir() b = BackupFile() b.backup_file(sdir,tdir)if __name__ == '__main__': main()
file_init:
#!/usr/bin/python#coding=utf8#filename:file_init.pyclass FileBackupPath(object): def __init__(self): print 'initialized' self.sdir = [] self.tdir = '' def getsdir(self): return self.sdir def gettdir(self): return self.tdir def entersourcepath(self): once = raw_input("Tell me file backup source dir: ") self.sdir.append(once) x = raw_input("Do you have another path? [y]").lower() if x and x[0] =='y': self.entersourcepath() else: print "Source directory is collected" def entertargetpath(self): self.tdir = raw_input("Tell me file backup target dir: ")
file_backup_start:
#!/usr/bin/python#coding=utf8#filename:file_backup_run.pyimport osimport timeclass BackupFile(object): def backup_file(self, sdir, tdir): self.source = sdir self.target_dir = tdir print self.source print self.target_dir today = self.target_dir + time.strftime('%Y%m%d') now = time.strftime('%H%M%S') comment = raw_input('Enter a comment --> ') if len(comment) == 0: self.target = today + os.sep + now + '.tar.gz' else: self.target = today + os.sep + now + '_' + comment.replace(' ', '_') + '.tar.gz' if not os.path.exists(today): os.mkdir(today) print 'Successfully create directory',today tar_command="tar -czf '%s' %s" %(self.target, ' '.join(self.source)) if os.system(tar_command) == 0: print 'Successful backup to', self.target else: print 'Backup Failed'
python 文件备份(类操作),首发于运维者。
我们可以冷静理智的给这些刺一一贴上标签:骄傲,自负,脆弱的自尊心,