def read(file,encoding='',mod='r',return_filename=False,print_detect_encoding=True,**ka): '''if return_filename: return content,f.name 1 not is 2 ^ SyntaxError: invalid syntax ''' file=autoPath(file) if not encoding and print_detect_encoding: U=py.importU() _pde=U.get_duplicated_kargs(ka,'print_encoding','p_encoding','p','pde','pEncoding','p_decode') if not _pde is U.GET_DUPLICATED_KARGS_DEFAULT: #记住绝对不能用 == print_detect_encoding=_pde if not return_filename: U=py.importU() return_filename=U.get_duplicated_kargs(ka,'returnFile','rf','rfn','return_file','return_name',) if py.is2():f=py.open(file,mod) else:#is3 encoding=encoding or detectEncoding(file,confidence=0.9,default='utf-8',p=print_detect_encoding) #utf-8 /site-packages/astropy/coordinates/builtin_frames/__init__.py {'confidence': 0.73, 'encoding': 'Windows-1252' f=py.open(file,mod,encoding=encoding) s=f.read() f.close() if return_filename: return s,f.name else: return s
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 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 getPaths(a): r''' a:str ''' U=py.importU() if U.iswin(): sp=a.replace('\\','/').split('/') rlist=[] def append(r): if r and r not in rlist:rlist.append(r) r='' for i,v in enumerate(sp): if len(v)>1 and v[-2] in T.AZ and v[-1]==':': append(r) r=v[-2:]+'/' continue for j in v: if j not in T.PATH_NAME: append(r) r='' continue if r and v: if isdir(r+v):r=r+v+'/' else: append(r) r='' continue return rlist else: raise NotImplementedError('*nux')
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 write_auto_filename(*a,**ka): all_args=py.importU().getArgsDict() return all_args U=py.importU() T=py.importT() sp=mkdir(U.gst+write_auto_filename.__name__) rf=[] for k,v in all_args.items(): fn='{}{}'.format(sp,T.filename_legalized(k)) if gb_write_auto_filename_len: len=U.len(v) if py.isint(len): fn+='={}'.format(len) f=write(fn ,v,autoArgs=False) rf.append(f) return rf
def test_dir_recursively(obj,*a): U=py.importU() if py.len(a)>TRY_MAX_LAYER:return r=U.dir(obj) for n,k,v in r: r[n][2]=test_dir_recursively(v,*a,k) or v return r
def get(p=False, edit=False, edit_prompt='', only_edit_firstline=True, **ka): '''win32con. CF_DSPTEXT ', 129], CF_OEMTEXT ', 7], CF_RETEXTOBJ ', 'RichEdit Text and Objects'], CF_TEXT ', 1], CF_UNICODETEXT ', 13], in py3 win32con.CF_TEXT return b' ' prompt [präm(p)t 不发音p] 提示 ; promte 提升 ''' U = py.importU() if U.istermux(): return U.cmd('termux-clipboard-get') p = U.get_duplicated_kargs(ka, '_print', 'print_', 'show', 'PRINT', default=p) edit = U.get_duplicated_kargs(ka, 'e', 'E', 'input_edit', 'input', 'edit_clipboard', default=edit) w.OpenClipboard() d = w.GetClipboardData(win32con.CF_UNICODETEXT) w.CloseClipboard() if p: U.pln(d) if edit: type = U.get_duplicated_kargs(ka, 'type', 'edit_type', 't') edit_prompt = U.get_duplicated_kargs(ka, 'title', 'msg', 'edit_msg', 'edit_prompt', 'prompt', 'promte', 'promot', 'promote', default=edit_prompt) only_edit_firstline = U.get_duplicated_kargs( ka, 'edit_firstline', 'firstline', 'fl', 'line0', 'l0', default=only_edit_firstline) if not edit_prompt: if py.istr(edit): edit_prompt = edit else: edit_prompt = '' if only_edit_firstline and py.len(d.splitlines()) > 0: d = d.splitlines()[0] d = U.input(edit_prompt, default=d, type=type) return d
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 setErr(ae): global gError U=py.importU() if U.gbLogErr:# U. if type(gError) is list:gError.append(ae) elif gError:gError=[gError,ae] else:gError=[ae] else: gError=ae if U.gbPrintErr:U.pln('#Error ',ae)
def set(aString, p=0): U = py.importU() if p: print("'''", aString, "'''") if U.istermux(): return U.cmd('termux-clipboard-set', input=aString) try: w.OpenClipboard() w.EmptyClipboard() # w.SetClipboardData(win32con.CF_TEXT, aString) w.SetClipboardText(aString) finally: w.CloseClipboard()
def getWindowByProcessName(name): ''' return [ [h,title,pid] ,...] ''' U = py.importU() r = [] ws = getAllWindows() for p in U.ps(name=name): for i in ws: if i[2] == p.pid: r.append(i) return r
def mouse_click(x=None, y=None, *a, _1=False): ''' click(*xy+(2,3)) == click(x,y,2,3) == click(x+2,y+3) ''' import win32api, win32con if not x and not py.isint(x): x = get_cursor_pos()[0] if not y and not py.isint(y): y = get_cursor_pos()[1] x, y = py.int(x), py.int(y) if not _1: if x == -1 or y == -1: U = py.importU() return x, U.IntRepr(y, repr='%s # -1 not click! #' % y) if a: if py.len(a) != 2: raise py.ArgumentError('a must be 2 int tuple') x = x + a[0] y = y + a[1] win32api.SetCursorPos((x, y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) return py.importU().object_custom_repr( (x, y), repr='Win.click({0},{1})'.format(x, y))
def __str__(self): U=py.importU() s='<{}'.format(numToSize(self) ) repr=U.get_duplicated_kargs(self.ka,'repr','str','s','st','__repr__','__str__',no_pop=True) if repr: if py.callable(repr): return repr(self, **self.ka ) else: return py.str(repr) return T.justify(s,**self.ka)+'>'
def getHomeFromEnv(): import os U=py.importU() if U.isLinux(): name='HOME' elif U.isWin(): name='USERPROFILE' else: raise EnvironmentError('#TODO system case') r=U.getEnv(name) r=autoPath(r) if not r.endswith('/'):r=r+'/' return r
def name(a): '''Anti abs 得到 单独文件(夹)名字 ''' U=py.importU() if not U.T.istr(a):return '' if U.inMuti(a,'/','\\',f=str.endswith):a=a[:-1] if not isAbs(a):return a else: a=T.sub(a,dir(a)) # U.repl() if U.inMuti(a,'/','\\',f=str.startswith):return a[1:] else:return a
def mouse_drag(x, y, x2=0, y2=0, time=1.1): import pyautogui U = py.importU() if U.len(x) == 2: if U.len(y) == 2: if x2 or y2: raise py.ArgumentError('duplicated x2,y2', x2, y2) x2, y2 = y x, y = x pyautogui.moveTo(x, y) pyautogui.mouseDown(button='left') pyautogui.dragTo(x2, y2, 1, button='left') U.sleep(time) pyautogui.mouseUp(button='left')
def writeIterable(file,data,end='\n',overwrite=True,encoding=None): U=py.importU() if not encoding:encoding=U.encoding file=autoPath(file) if overwrite:new(file) if py.is2():f=py.open(file,'a') else: f=py.open(file,'a',encoding=encoding) for i in data: f.write(py.str(i)+end) f.close() return f.name
def nt_path(fn): '''if linux etc ,will auto ignored write success, read failed ? ''' U=py.importU() fn=_p.abspath(fn) if U.iswin():#or cyg? if not py.isunicode(fn):fn=fn.decode(U.T.detect(fn))#暂时没想到更好方法,头晕 fn=fn.replace(u'/',u'\\') if u"\\\\?\\" in fn: pass elif fn.startswith(u"\\\\"): fn=u"\\\\?\\UNC\\" + fn[2:] else: fn=u"\\\\?\\" + fn return fn
def getVersionNumberCmdVer(): ''' Microsoft Windows [版本 10.0.16299.125] Microsoft Windows [版本 6.1.7601] Microsoft Windows XP [版本 5.1.2600] ''' U = py.importU() import subprocess as sb T = U.T r = sb.Popen('cmd.exe /c ver', stdout=sb.PIPE) r = r.stdout.read(-1) r = T.subLast(r, ' ', ']') r = r.split('.') if len(r) < 3: raise Exception('cmd ver ', r) major, minor, build = r[:3] return float('{0}.{1}'.format(major, minor))
def recursive_test_dp(r): U=py.importU() if py.isdict(r) or py.getattr(r,'items',0): r=[[n,k,v] for n,(k,v) in py.enumerate(r.items()) ] if py.islist(r) or py.isdict(r): pass else:return r for n,k,v in r: try: b=dill_dump_bytes(v) r[n][2]=U.size(b) except Exception as e: r[n][2]=recursive_test_dp(v) return r
def write(file,data,mod='w',encoding='utf-8',mkdir=False,autoArgs=True,pretty=True,seek=None): '''py3 open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) py2 open(name[, mode[, buffering]]) pretty=True Format a Python object into a pretty-printed representation. ''' U=py.importU() try: if autoArgs: if py.istr(data) and py.len(file)>py.len(data)>0: if '.' in data and '.' not in file and isFileName(data): file,data=data,file U.warring('F.write fn,data but seems data,fn auto corrected(v 纠正') except:pass # try: file=autoPath(file) if not encoding:encoding=U.encoding if mkdir:makeDirs(file,isFile=True) # if 'b' not in mod and py.isbytes(data):mod+='b'# 自动检测 data与 mod 是否匹配 if 'b' not in mod: #强制以 byte 写入 mod+='b' f=py.open(file,mod) #f.write(强制unicode) 本来只适用 py.is3() ,但 py2 中 有 from io import open if py.isint(seek): f.seek(seek) # with open(file,mod) as f: if py.isbyte(data):#istr(data) or (py.is3() and py.isinstance(data,py.bytes) ) : f.write(data) elif (py.is2() and py.isinstance(data,py.unicode)) : f.write(data.encode(encoding)) elif (py.is3() and py.istr(data)): # if 'b' in mod.lower(): f.write(data.encode(encoding)) # else:f.write(data)#*** UnicodeEncodeError: 'gbk' codec can't encode character '\xa9' in else: # if py.is2():print >>f,data # else: if pretty: data=U.pformat(data) U.pln(data,file=f) f.close() return f.name
def isAbs(file): '''in cygwin: In [43]: U.path.isabs( 'M:/Program Files/.babun/cygwin/lib/python2.7/qgb/file/attr.html') Out[43]: False In [45]: U.path .isabs('M:\\Program Files\\.babun\\cygwin\\lib\\python2.7\\qgb\\file\\attr.html' ) Out[45]: False ##### win py3.6 fixed --------> F.isabs('2d:\1\2')# False --------> F.isabs('d:\1\2')# False --------> F.isabs('/babun/cygwin/lib/python2.7\\qgb\\F.py')# True #TODO 更加精细判断,文件名不合法 return None? ''' U=py.importU() if U.iscyg() or U.iswin(): if ':' in file:return True else:return False return _p.isabs(file)
def getLastError(errCode=None, p=True): ''' need .decode('gb18030') ''' U = py.importU() from ctypes import c_void_p, create_string_buffer GetLastError = kernel32.GetLastError FormatMessage = kernel32.FormatMessageA LocalFree = kernel32.LocalFree FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100 FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000 FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200 try: msg = create_string_buffer(256) FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, c_void_p(), 2, 0, msg, len(msg), c_void_p()) except Exception as e: U.pln(e) # return 233 # from win32con import ( # FORMAT_MESSAGE_FROM_SYSTEM, # FORMAT_MESSAGE_ALLOCATE_BUFFER, # FORMAT_MESSAGE_IGNORE_INSERTS) if errCode is None: errCode = GetLastError() U.pln(errCode) message_buffer = ctypes.c_char_p() FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, None, errCode, 0, ctypes.byref(message_buffer), 0, None) error_message = message_buffer.value LocalFree(message_buffer) r = '{} - {}'.format(errCode, error_message.decode('mbcs')) #unicode # if py.is2(): # else: r= '{} - {}'.format(errCode, error_message) # error_message = error_message.decode('cp1251').strip() if U.isipy() and not U.DEBUG: #TODO 如果修改了repr 方式 可以去除这个 U.pln(r) else: return r
def main(): U = py.importU() py.pdb() # U=globals()['U']# 为何在此不能自动引用 globals import U U.pln(getAllNetwork()) exit() import sys, os sys.path.append('d:\pm') from qgb import U, T, F o = getVersionInfo() U.pln(o.dwMajorVersion, o.dwMinorVersion) # CreateProcessWithLogonW( # lpUsername='******', # lpPassword='******', # lpApplicationName=r'C:\WINDOWS\system32\calc.exe') U.pln('[%s]' % getTitle(), getProcessPath(), U.getModPath())
def try_dill_dump_recursively(obj,*a,): global U if not U:U=py.importU() if py.len(a)>TRY_MAX_LAYER:return try: b=dill_dump_bytes(obj) return (*a,U.size(b)) except Exception as e: if py.islist(obj) or py.istuple(obj) or py.isset(obj): r=[] for n,v in py.enumerate(obj): r.append([n,try_dill_dump_recursively(v,*a,n)]) return r elif py.isdict(obj): d={} for n,(k,v) in py.enumerate( obj.items()): d[n]=try_dill_dump_recursively(kv,*a,n) return d r=[] for n,k,v in U.dir(obj): r.append([k,try_dill_dump_recursively(v,*a,k)])
def auto_path(fn,ext='',default='',is_dir=False,p=False): ''' default is U.gst if fn.startswith("."): 如果路径中所有文件夹存在,则可以写入读取。否则无法写入读取。file io 都是这个规则吧 FileNotFoundError: [Errno 2] No such file or directory: '. #TODO #BUG# F.auto_path('\\\\\\C:\\test\\clipboard',default='C:/test/',)== '///C:/test/clipboard' ''' U=py.importU() if not gbAutoPath: pass else: if default: default=default.replace('\\','/') if not default.endswith('/'):default+='/' else: default=U.set_test_path(U.gst) # 防止 U.gst 被改变没被保存 fn=str(fn) fn=fn.replace('\\','/') if ext and not ext.startswith('.'):ext='.'+ext if not fn.lower().endswith(ext.lower()):fn+=ext if fn.startswith("~/"): import os if U.isnix(): home=os.getenv('HOME') else: home=os.getenv('USERPROFILE')# 'C:/Users/Administrator' not cyg home os.getenv('HOME') # else: home=os.getenv('HOMEPATH')# HOMEPATH=\Users\Administrator fn= home+fn[1:]; #TODO to avoid dos max_path , must \ full path 2019年12月19日 不记得什么意思? if (not fn.startswith(".")) and (not isAbs(fn)) : while fn.startswith('/'):fn=fn[1:] fn= default + fn if py.len(fn)>=260 and U.iswin(): fn=nt_path(fn) if(is_dir and not fn.endswith('/')):fn+='/' if p:print(fn) return fn
def GetProcessImageFileName(pid=None): '''if pid ignore Process name Windows XP or later Windows Server 2003 and Windows XP: The handle must have the PROCESS_QUERY_INFORMATION access right.''' if not pid: U = py.importU() pid = U.pid PROCESS_ALL_ACCESS = 0x001F0FFF # bInheritHandle [in] # If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle. hprocess = kernel32.OpenProcess(PROCESS_ALL_ACCESS, True, pid) dll = windll.psapi from ctypes import c_void_p, create_string_buffer im = 256 fn = create_string_buffer(im) if dll.GetProcessImageFileNameA(hprocess, fn, im) == 0: return False else: fn = fn.value for d, v in getAllDisk().items(): if fn.startswith(v): return fn.replace(v, d) return fn
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