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 walk(ap): ''' return tuple(ap,dir_list,file_list ) 2&3 : os.walk(top, topdown=True, onerror=None, followlinks=False) ''' if py.is2(): return _os.walk(ap).next() else: return _os.walk(ap).__next__()
def getAllWindows(): ''' return [ [h,title,pid] ,...] ''' mlst = [] win32gui.EnumWindows(EnumWindowsProc, mlst) # for handle in handles: # mlst.append(handle) if py.is2(): return [(i[0], i[1].decode('mbcs'), get_pid_by_hwnd(i[0])) for i in mlst] else: return [(i[0], i[1], get_pid_by_hwnd(i[0])) for i in mlst]
def get_title(h=0, size=1024): '''h:window Handle''' if not h: h = getCmdHandle() if py.is2(): # size= user32.GetWindowTextLengthA(h) + 1 # always =2 in py3? title = ctypes.create_string_buffer(size) user32.GetWindowTextA(h, title, size) else: length = user32.GetWindowTextLengthW(h) + 1 title = ctypes.create_unicode_buffer(length) user32.GetWindowTextW(h, title, length) return title.value
def CommandLineToArgvW(cmd): import ctypes if py.is2(): cmd = py.unicode(cmd) nargs = ctypes.c_int() ctypes.windll.shell32.CommandLineToArgvW.restype = ctypes.POINTER( ctypes.c_wchar_p) lpargs = ctypes.windll.shell32.CommandLineToArgvW(cmd, ctypes.byref(nargs)) args = [lpargs[i] for i in range(nargs.value)] if ctypes.windll.kernel32.LocalFree(lpargs): raise AssertionError return args
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 msgbox(s='', st='title', *a): ''' __import__('ctypes').windll.user32.MessageBoxW(0, 'text', 'title', 0) ''' if (a): a = py.list(a) a.insert(0, s) a.insert(1, st) st = 'length %s' % len(a) s = str(a) # s=str(s)+ ','+str(a)#[1:-2] if py.is2(): return user32.MessageBoxA(0, str(s), str(st), 0) else: return user32.MessageBoxW(0, str(s), str(st), 0)
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
try: try: from . import py except: import py U = py.importU() if U.isipy(): __all__.append('ipy') # import ipy # ipy.gipy.autocall=2# 放到 qgb.ipy中 # ipy.gi.setModule() # U.replaceModule('ipy',ipy.gi,package='qgb',backup=False) # ipy=ipy.gi#少了这个,ipy在sys.modules 中虽然已经替换,但是实际使用却还是原来module ,? # ipy.startRecord() # M:\Program Files\.babun\cygwin\home\qgb\.ipython\profile_default\history.sqlite if U.iswin() or (py.is2() and U.iscyg()): __all__.append('Win') # U.pln( __all__ except Exception as e: if 'gError' in dir(): gError.append(e) else: gError = [e] # U.pln( __name__ # sys.argv==['-c'] # U.repl() # if __name__=='__main__': #此句在 python -m qgb中不会执行,始终为'qgb', why? #TODO #TOKNOW # U.pln( __all__ # try: # f=sys._getframe() # while f and f.f_globals and 'get_ipython' not in f.f_globals.keys():
#coding=utf-8 try: if __name__.startswith('qgb.Win'): from .. import py else: import py except Exception as ei: raise ei raise EnvironmentError(__name__) if py.is2(): import _winreg as winreg from _winreg import * else: import winreg from winreg import * def get(skey, name, root=HKEY_CURRENT_USER, returnType=True): ''' from qgb.Win import reg reg.get(r'Software\Microsoft\Windows\CurrentVersion\Internet Settings','ProxyEnable') reg.get(r'HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\Size' ) There are seven predefined root keys, traditionally named according to their constant handles defined in the Win32 API skey不能包含 name,否则 FileNotFoundError: [WinError 2] 系统找不到指定的文件。 ''' r = OpenKey(root, skey) r = QueryValueEx(r, name) if returnType: return r[0], '{} : {}'.format(REG_TYPE[r[1]], r[1]) else: return r[0]
def save(file=None,lines=-1,tryExcept=False,out=False,columns=70,overide=True,del_other=False,out_max=9999,**ka): '''file is str or (mod a) 在没有ipython实例时,不能get_ipython() 当file被指定时,overide 参数无效 #BUG #TODO 出现输入记录不同步的现象,应该添加一个报警 In [302]: _i265 Out[302]: '[i for i in sku if i[0] in [0.03, 0.04, 0.05, 0.06, 0.07, 0.18] ]' In [303]: In[265] Out[303]: 'page=pa=await tb.get_or_new_page(U.cbg(e=1))' ''' del_other=U.get_duplicated_kargs(ka,'delOther','delete','delattr',default=del_other) if ka:raise py.ArgumentError('没有处理这个ka,是不是多传了参数',ka) try: if py.isint(lines) and lines>0: # lsta,lend=0,lines lsta,lend=lines,-1 elif len(lines)==2: lsta,lend=lines lsta=lsta if lsta>0 else 0 else:raise Exception except: lsta,lend=0,gIn.__len__() if file:#当指定file 名时,总是 overide if T.istr(file): file=T.filename(file)[:255-3]# 如果用 pathname 不好处理 含有 /斜杠的问题 if U.is_linux(): while py.len(file.encode('utf-8'))> 255-3: # 256-3 too long ! file=file[:-1] file=F.autoPath(file,ext='.py',default=gsavePath) #255-3(.py) 防止文件名过长 OSError: [Errno 22] Invalid argument: "\\\\?\\C:\\test F.new(file) if py.is2():file=open(file,'a') else:file=open(file,'a',encoding="utf8") elif py.isfile(file): if file.mode!='a':raise Exception('file mode should be "a" ') else: raise Exception('invalid argument file') else: if gdTimeName and overide: file=gdTimeName[py.list(gdTimeName.keys() )[-1]]#is3:TypeError: 'dict_keys' object does not support indexing file=F.autoPath(file,ext='.py',default=gsavePath) if py.is2():file=open(file,'w') else:file=open(file,'w',encoding="utf8") # last=-1 # for t in gdTimeName: # if t>last:file,last=name,d # last=gdTimeName.values() # last.sort()#从小到大排序,ACS正序, DESC倒序 Ascending and Descending # file=[n for n,d in gdTimeName.items() if d==last[-1]][0] else: file='{0}{1}.py'.format(gsavePath,U.stime()) if py.is2():file=open(file,'a') else:file=open(file,'a',encoding="utf8") U.pln(gshead,file=file) ####### get exec_lines to gsqgb gsqgb=U.main(display=False) #join( <traitlets.config.loader.LazyConfigValue at 0x20066295400> ) ### TypeError: can only join an iterable gsexec_lines=U.getNestedValue(gipy.config,'InteractiveShellApp','exec_lines') #_class%20'traitlets.config.loader.LazyConfigValue'_.html if not py.iterable(gsexec_lines): gsexec_lines=[] gsexec_lines=' ;'.join(gsexec_lines) if gsexec_lines: if not 'from qgb import' in gsexec_lines: gsqgb='{0}\n{1}'.format(gsqgb,gsexec_lines) else:gsqgb=gsexec_lines U.pln(gsqgb+'\n',file=file ) # print >>file,'import sys;sys.path.append('{0}');from qgb import *'.format(gspath) #using single quote for cmd line #-4 为了去除 /qgb #ipython --InteractiveShellApp.exec_lines=['%qp%'] 不会改变In[0],始终为'' for i,v in enumerate(gIn[lsta:lend]): skip=False if i==0 and lsta==0:continue i=lsta+i v=v.strip() # U.isSyntaxError(u'_{0}={1}'.format(i,v) ) : # pass if i in gOut: if i==1 and py.istr(gOut[1]) and gOut[1].endswith(':/QGB/babun/cygwin/lib/python2.7/'): pass else: v=u'_{0}={1}'.format(i,v) if U.isSyntaxError(v) or U.multin(gIgnoreIn,v): # or u'from qgb import *' in v or sum(map(lambda a:v.startswith(a),gIgnoreStart) ): v=u'#'+v skip=True if tryExcept and (not skip): v='#########################\n\t'+v if py.is2():v=gsTryExcept.format(i,v).encode('utf-8') else:v=gsTryExcept.format(i,v) U.p(v,file=file ) else: if py.is2():v=v.encode('utf-8') else:pass U.p(v,' '*(columns-len(v.splitlines()[-1])),file=file ) if out and (i in gOut) and (not skip): pout=pformat(gOut[i]) if py.len(pout) > out_max: pout='#Warning# len(pout)={} > out_max'.format(py.len(pout)) print( '#ipy.save In[{}]{}# len(pout)={} > out_max'.format(i,gIn[i],py.len(pout)) ) U.pln(';"""#{0}'.format(i),file=file ) # U.pln('"""',file=file ) U.pln(pout,file=file ) U.pln('"""',file=file ) else: U.pln('#',i,file=file ) # if i in [14]:import pdb;pdb.set_trace()#U.repl() # gipy.magic(u'save save.py 0-115') # U.pln(gIn # U.pln(gOut.keys() file.close() gdTimeName[U.time()]=file.name if del_other: for t,f in gdTimeName.items(): if f == file.name:continue print('del:',U.stime(t),F.delete(f) or [f,False]) return '{0} {1} success!'.format(save.name,file.name)