def deleteFile(file): file=autoPath(file) sp=getSplitor(file) # for i in a.split(ap): U=py.importU() def Error(): #Error() 返回None时 #TypeError: catching classes that do not inherit from BaseException is not allowed return FileNotFoundError #issubclass(FileNotFoundError,WindowsError) == True if U.iswin(): return WindowsError try: if isDir(file): import shutil shutil.rmtree(file, ignore_errors=True)#这里不发出 异常 return file _os.remove(file)#异常 是从这里产生的 return file except FileNotFoundError as e: if isDir(file): raise Exception('#TODO') return py.No(file,e,'Not exists?') #Error {'G:\\test\\npp': WindowsError(5, '')} # Docstring: MS-Windows OS system call failed. #*nix NameError: name 'WindowsError' is not defined ''' except Exception as e: # setErr({file:e}) return py.No(file,e) return False
def stat(path, dir_fd=None, follow_symlinks=True): U=py.importU() IntSize,FloatTime,IntOct=U.IntSize,U.FloatTime,U.IntOct import os try: if isinstance(path,os.stat_result): s=path else: s=os.stat(path=path, dir_fd=dir_fd, follow_symlinks=follow_symlinks) # return [ # path, # IntSize(s.st_size), # FloatTime(s.st_atime), # FloatTime(s.st_mtime), # FloatTime(s.st_ctime), # IntOct (s.st_mode ), # ] except Exception as e: return py.No(e) r={} for i in py.dir(s): if not i.startswith('st_'):continue v=getattr(s,i,py.No('Error getattr') ) if i=='st_size':r[i]=IntSize(v);continue if i=='st_mode':r[i]=IntOct(v) ;continue if i.endswith('time'): r[i]=FloatTime(v) continue r[i]=v return r
def size_single_file(f): f=nt_path(f) size =0 #0L SyntaxError in 3 if not _p.exists(f): return py.No('{} NOT EXISTS!'.format(f)) if _p.isdir(f): # if f=='' , _p use pwd return py.No('{} is dir !'.format(f)) try: size= _p.getsize(f) if size<=0: size=py.len(read_bytes(f)) except Exception as e: return py.No('unexcept err',e,f)
def ll(ap='.',readable=True,type='',t='',r=False,d=False,dir=False,f=False,file=False, return_dict=True,no_raise=True,**ka): '''return {file : [size,atime,mtime,ctime,st_mode]} readable is True: Size,Stime,.. linux struct stat: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html''' dr={} for i in list(ap,type=type,t=t,r=r,d=d,dir=dir,f=f,file=file):#ls 肯定返回 list类型! # importU;if U.DEBUG:U.pln ap,repr(i) try: s=_os.stat(i) except: continue if readable: U=py.importU() IntSize,FloatTime,IntOct=U.IntSize,U.FloatTime,U.IntOct try: dr[i]=[ IntSize(size(i)), FloatTime(s.st_atime), FloatTime(s.st_mtime), FloatTime(s.st_ctime), IntOct (s.st_mode ), ] except Exception as e: if no_raise: dr[i]=py.No(e) else: raise else: dr[i]=[size(i),s.st_atime,s.st_mtime,s.st_ctime,s.st_mode] if return_dict: return dr else: return [[k,*v] for k,v in dr.items()]
def exists(fn,zero=True): ''': path.exist('c:') Out[57]: False In [58]: path.exist('o:')#这是因为当前目录下存在 'o:',但是只能用ls完整查看 Out[58]: True ## 在cygwin中 只能判断 c:\ 或 c:/ ,单独 c: 总为False ############# >>> path.exists('c:') True >>> path.exists('o:') True ''' if not fn:return fn U=py.importU() if U.iscyg(): if len(fn)==2 and fn[-1]==':':fn+='/' # raise NotImplementedError if _p.exists(fn): if _p.isdir(fn): fn=fn.replace('\\','/') if not fn.endswith('/'):fn+='/' return fn if _p.getsize(fn)<1 and not zero: return zero return fn else: return py.No(fn,'not exists')
def get_image(file=None, format='png'): ''' :param fp: A filename (string), pathlib.Path object or file object. KeyError: '.PNG' [format not contains . ] ''' global gsdir U, T, N, F = py.importUTNF() if not gsdir: gsdir = U.get_or_set('clipboard.dir', lazy_default=lambda: F.md(U.gst + 'clipboard')) from PIL import ImageGrab, Image im = ImageGrab.grabclipboard() if im and file: # if not im: # return if not F.isAbs(file): file = gsdir + file if not file.lower().endswith(format.lower()): file = file + '.' + format im.save(file, format) return file elif not im: return py.No('can not get clipboard image') return im
def get_pid_by_hwnd(hwnd): try: import win32process threadid, pid = win32process.GetWindowThreadProcessId(hwnd) except Exception as e: pid = py.No(e) return pid
def writeYaml(file,obj): import yaml try: with py.open(file,'w') as f: yaml.dump(obj,f,default_flow_style=False)#default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style: return file except Exception as e: return py.No(e,file,obj)
def isFileName(a): '''a:str''' # from . import U #ValueError: Attempted relative import in non-package U=py.importU() for i in a: if i not in T.PATH_NAME:return py.No(i,a) return a
def getMode(file): import os try: r= oct(os.stat(file).st_mode) if r[:5]!='0o100':raise Exception('不是100代表什么?',r) return r[-3:] except Exception as e: return py.No(e)
def dill_load_file(file,dill_ext='.dill'): import dill dill.settings['ignore']=False #KeyError: 'ignore' file=auto_path(file,ext=dill_ext) try: with py.open(file,'rb') as f: return dill.load(f) except Exception as e:#TODO all load save py.No return py.No(file,e)
def include(file,keyword): if py.isbyte(keyword):mod='rb' else:mod='r' try: with py.open(file,mod) as f: for i in f: if keyword in i:return True except Exception as e: return py.No(e) return False
def format(obj,width=79,max_seq_length=py.No("auto get-set 'ipy.pformat.max_seq_length' ",no_raise=1)): ''' IPython.lib.pretty.pretty( obj, verbose=False, max_width=79, newline='\n', max_seq_length=1000, ) /IPython/core/formatters.py: format(obj, include=None, exclude=None) Docstring: Return a format data dict for an object. By default all format types will be computed. The following MIME types are usually implemented: * text/plain * text/html * text/markdown * text/latex * application/json * application/javascript * application/pdf * image/png * image/jpeg * image/svg+xml Parameters ---------- obj : object The Python object whose format data will be computed. include : list, tuple or set; optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list, tuple or set; optional A list of format type string (MIME types) to exclude in the format C:\QGB\Anaconda3\lib\site-packages\IPython\core\formatters.py :89 ''' import IPython.lib.pretty if not max_seq_length: max_seq_length=U.get_or_set('ipy.pformat.max_seq_length',2000) U.set('ipy.pformat.max_seq_length',max_seq_length) return IPython.lib.pretty.pretty(obj,max_width=width,max_seq_length=max_seq_length) from IPython.core.interactiveshell import InteractiveShell r= InteractiveShell.instance().display_formatter.format(obj) if py.len(r)!=2 or py.len(r[1])!=0 or not py.isdict(r[0]):raise EnvironmentError() return U.get_dict_value(r[0])
def size(asf,int=py.No('ipython auto readable')): '''file or path return byte count not exist return -1''' asf=nt_path(asf)#if linux etc ,will auto ignored # asf=autoPath(asf)#in there,can't use gst size =0 #0L SyntaxError in 3 if not _p.exists(asf): return py.No('{} NOT EXISTS!'.format(asf)) if not _p.isdir(asf): size= _p.getsize(asf) if size<=0: try:size=len(read_bytes(asf)) except Exception as e: return py.No('unexcept err',e,asf) # return size else:# is dir for root, dirs, files in _os.walk(asf): size += sum([_p.getsize(_p.join(root, name)) for name in files]) U=py.importU() # U.msgbox(U.is_ipy_cell()) if not int :#and U.is_ipy_cell(): size=U.IntSize(size) return size
def read_bytes(file,size=-1,): '''is2 rb return str f.read(size=-1, /) Read and return up to n bytes. ''' import io if isinstance(file, io.BytesIO): file.seek(0) return file.read(-1) file=autoPath(file) try: with py.open(file,'rb') as f: return f.read(size) except Exception as e: return py.No(e,file)
def move(source,target,edit_target=False,mkdir=True,remove_invalid_char=True,**ka): ''' * in target == source ? in target == source_fn // in target == path(exclude source_fn) # os.rename(source, target) #OSError: [WinError 17] 系统无法将文件移到不同的磁盘驱动器。: 'C: os.rename target文件名(包不包括路径都没关系)包括扩展名,最大不能超过241 ''' U,T,N,F=py.importUTNF() edit_target=U.get_duplicated_kargs(ka,'e','edit','editarget',default=edit_target) remove_invalid_char=U.get_duplicated_kargs(ka,'remove_char','delChar', 'del_char','remove_illegal','del__illegal','del_invalid','remove_invalid', 'del_invalid_char','del__illegal_char','remove_illegal_char',default=remove_invalid_char) source=F.autoPath(source) source_fn=F.get_filename_from_full_path(source) source_path=source[:-py.len(source_fn)] if target.endswith('/'): target+=source_fn # if '*' in target: target=target.replace('*',source) target=target.replace('?',source_fn) target=target.replace('//',source_path) target=F.autoPath(target) if edit_target:target=U.input(default=target) if remove_invalid_char: if U.is_windows(): target=T.replacey(target,T.NOT_PATH_NAME_WINDOWS,'') if not target.endswith('/') and F.isDir(target): target=target+'/' if mkdir:F.mkdir(F.get_dir(target)) # 要先有文件夹,不然shutil.move有可能找不到 import shutil try: return shutil.move(source, target) # return target except (FileNotFoundError,FileExistsError) as e: # parentheses required, otherwise invalid syntax return py.No(e,source,target) if F.isDir(target): r=target+source_fn else: r=target return F.exist(r)
def detect_file_encoding(file,confidence=0.7,default=py.No('not have default encoding'),buffer_size=9999,p=True,**ka): U,T,N,F=py.importUTNF() p=U.get_duplicated_kargs(ka,'print_file_encoding','print_detect_encoding','print',default=p,no_pop=True) if py.istr(file): with py.open(file,'rb') as f: b=f.read(buffer_size) elif py.isfile(file): if 'b' not in file.mode:raise py.ArgumentError("'b' not in file.mode",file) i=file.tell() b=file.read(buffer_size) file.seek(i) else:raise py.ArgumentError('need str or file') c= T.detect(b,confidence=confidence,default=default) if p:print(file,c) #TODO U.get_or_set('detect_file_encoding.p',True) return c
def read_sqlite(file,table='',sql="SELECT * FROM {};"): file=autoPath(file) if table:sql=sql.format(table) import sqlite3 with sqlite3.connect(file) as con: cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") #[('sessions',), ('sqlite_sequence',), ('history',), ('output_history',)] tables=[i[0] for i in cursor.fetchall()] if table: if not (table in tables):return py.No('no table',table,'found in',file) cursor.execute(sql ) return cursor.fetchall() else: r={} for i in tables: r[i]=read_sqlite(file=file,table=i) return r
def readlines(a,EOL=True,encoding=None,str_repr=False): a=autoPath(a) if not encoding: encoding=detectEncoding(a) def _return(lines): if str_repr: U=py.importU() return [U.StrRepr(i) for i in lines] return lines try: if EOL: r=[] for i in py.open(a,encoding=encoding):r.append(i) else: r=read(a,encoding=encoding).splitlines() return _return(r) except Exception as e: return py.No(e)
def read_multi_files_return_bytes_list(*fs,max_size=8*1024*1024,return_all_bytes=False): r=[] def append(a): if return_all_bytes and not a: return r.append(b'') r.append(a) for f in fs: s=size_single_file(f) if not s : append(s) continue if s>max_size: append(py.No('f > max_size',f,max_size)) continue with py.open(f,'rb') as fp: b=fp.read(max_size) append(b) return r
def setWindowPos(hwnd=0, x=0, y=0, w=0, h=0, rect=(), top=None, flags=None): '''if not flags:flags=SWP_SHOWWINDOW # 无论是否top,是否拥有焦点,默认显示此窗口 ''' if not hwnd: hwnd = getCmdHandle() # if x==y==w==h==0 and not rect: # x,y,w,h=(199,-21,999,786) if not rect: rect = getWindowPos(hwnd) if not x: x = rect[0] if not y: y = rect[1] if not w: w = rect[2] - rect[0] if not h: h = rect[3] - rect[1] if top: top = HWND_TOPMOST else: top = HWND_NOTOPMOST #-2 if not flags: flags = SWP_SHOWWINDOW # 无论是否top,是否拥有焦点,默认显示此窗口 if user32.SetWindowPos(hwnd, top, x, y, w, h, flags): #1 return hwnd else: return py.No(getLastError())
def SetForegroundWindow(title=None, handle=None, pid=None, process_name='', raise_error=0, retry=99, **ka): U, T, N, F = py.importUTNF() if py.isint(title) and not handle: handle, title = title, '' if not title: title = U.get_duplicated_kargs( ka, 't', ) if not handle: handle = U.get_duplicated_kargs(ka, 'hwnd', 'h') if not process_name: process_name = U.get_duplicated_kargs(ka, 'name', 'pn', 'process') no_raise = U.get_duplicated_kargs(ka, 'no_raise', 'noRaise', 'no_raise_err', default=not raise_error) raise_error = (not no_raise) or U.get_duplicated_kargs( ka, 'err', 'error', 'exp', 'exception', 'Exception', 'raise_err', 'raise_error', 'raiseError', 'raiseErr', 'raise_EnvironmentError', 'EnvironmentError', 'raiseEnvironmentError', default=raise_error) if not handle and not title and not pid and not process_name: handle = get_current_cmd_windows() if not handle: from qgb import Win for h, t, p in Win.getAllWindows(): if t == title or p == pid: handle = h break if process_name and process_name == U.get_process_name_by_pid(p): handle = h break else: if (not title) and (not process_name): raise py.ArgumentError(py.locals()) for h, t, p in Win.getAllWindows(): if title and title in t: handle = h break if process_name and process_name in U.get_process_name_by_pid( p): handle = h break else: if raise_error: raise py.EnvironmentError( 'cannot find ForegroundWindow title : ' + a) # if py.isint(title): # handle=title # else: # raise py.ArgumentError('foreground,a',row) import win32gui # if not win32gui.IsWindowVisible(handle): #先不考虑 try: # win32gui.SetForegroundWindow(handle) import win32gui, win32com.client, win32con, pythoncom pythoncom.CoInitialize( ) #加上这句解决 #pywintypes.com_error: (-2147221008, '尚未调用 CoInitialize。', None, None) shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys('%') ##For ALT prefix with % win32gui.ShowWindow(handle, win32con.SW_SHOW) win32gui.SetForegroundWindow(handle) except Exception as e: #BUG 窗口在后台,通过 http_rpc 调用此函数,第一次总会出错:,第二次才成功? # error(0, 'SetForegroundWindow', 'No error message is available') if 'No error message is available' in repr(e): for i in py.range(1, retry): try: if i % 9 == 1: U.sleep(0.01) # sleep一下有奇效,为什么? win32gui.SetForegroundWindow(handle) return U.IntCustomRepr( handle, repr='Win.set_foreground(%r) #retry:%s' % (handle, i)) except: pass # return py.No(e,'') if raise_error: raise return py.No(e) return U.IntCustomRepr(handle, repr='Win.set_foreground(%r)' % handle)
def getWindowHandleByTitle(title): for i in getAllWindows(): if title in i[1]: return i[0] return py.No('not found window title', title)
def makeDirs(ap,isFile=False,cd=0,no_auto_path=False): ''' 访问移动硬盘时,可能出现已经创建成功,但是 F.ls 看不到的情况。 用explorer访问后又正常 ''' U=py.importU() if not no_auto_path:ap=autoPath(ap) if not py.isbool(isFile) and not py.isint(isFile): U.log('F.md(str,isFile={})'.format(repr(isFile))) if py.is3(): from pathlib import Path p=Path(ap).absolute() if isFile: return makeDirs(p.parent,isFile=False) if p.is_file():#if not exists, is_dir() is_file() both return False return py.No(ap+' exists , and it is a file') r=py.No('unexpected err') try: p.mkdir() except (FileNotFoundError,) as e: if p.parent==p:# 'D:\\' 驱动器不存在 r=e else: r=makeDirs(p.parent,isFile=False) if r:p.mkdir() # 建立父目录后,再次尝试创建本目录 else:return r # else:return r #但是如果父目录本来是个文件,再mkdir则FileNotFoundError: [WinError 3] 系统找不到指定的路径。 except FileExistsError: pass except Exception as e: r=e if p.exists(): if not no_auto_path:sp=autoPath(p) else:sp=py.str(p.absolute()).replace('\\','/') if p.is_dir() and not sp.endswith('/'): sp+='/' r=sp else: r=py.No(r,p) if r and cd:U.cd(r) return r # if py.is2(): ######################################### U=py.importU() sp=getSplitor(ap) ap=ap.split(sp) if isFile:ap=ap[:-1] # if not isabs(ap): # if not ap.startswith('.'): # if ap.startswith(sp):ap=U.gst[:-1]+ap # else:ap=U.gst+ap # else: base='' for i in ap: base+=(i+sp) #TODO 2019-1-19 未处理存在的是文件 而不是 文件夹的情况 if exist(base):continue else: try: _os.mkdir(base) except Exception as e: if U.iswin(): if e.winerror==5:continue#WindowsError(5, '') 拒绝访问 if e.winerror==183:continue#WindowsError 183 当文件已存在时,无法创建该文件。 if 'exists' in e.args[1]:#(17, 'File exists') cygwin; continue # U.repl(printCount=True) setErr(e) return False return True
def list(ap='.',type='',t='',r=False,d=False,dir=False,f=False, file=False,include='',exclude='',timeout=None,print_result=False,**ka): '''Parms:bool r recursion str (type,t) '(d,f,a,r)' default return all''' U=py.importU() print_result=U.get_duplicated_kargs(ka,'print_r','print','p',default=print_result) if dir:d=True if file:f=True if t and not type:type=t if 'd' in type:d=True if 'f' in type:f=True if 'a' in type:d=True;f=True if 'r' in type:r=True if d or dir or f or file:pass else:d=f=True #default return all if not py.istr(ap) or py.len(ap)<1: setErr('F.list arguments ap error') ap='.' # if len(ap)==2 and ap.endswith(':'):ap+='/' ap=ap.replace('\\','/') if not ap.endswith('/'):#U.inMuti(ap,'/','\\',f=str.endswith): if isDir(ap): ap+='/' else: return [exists(ap)] # if not ap.endswith('/'):ap+='/' # else:ap+='\\' # U.repl() ########## below r is result rls=[] try:r3=py.list(walk(ap)) except Exception as ew: # pln ap;raise ew return py.No(ew) if ap=='./':ap='' # U.repl() r3[1]=[ap+i+'/' for i in r3[1]] #dirs r3[2]=[ap+i for i in r3[2]] #files if d:rls.extend(r3[1]) # if r: for i in r3[1]:rls.extend(list(i,r=r,d=d,f=f)) if f:rls.extend(r3[2]) if include:rls=[i for i in rls if include in i] if exclude:rls=[i for i in rls if exclude not in i] if print_result: U.pprint(rls) return rls