def set(skey, name, value, root=HKEY_CURRENT_USER, type='auto,or REG_TYPE int', returnType=True): r = OpenKey(root, skey, 0, KEY_SET_VALUE) if not py.isint(type): if py.isint(value): type = 4 if py.istr(value): type = 1 if py.isbyte(value): type = 3 #TODO test,and add more rule SetValueEx(r, 'ProxyEnable', 0, type, value) if get(skey, name, root=root, returnType=False) == value: return 'reg.set [{}] {}={} sucess!'.format(skey[-55:], name, value) else: return 'reg.set [{}] {}={} Failed !'.format(skey, name, value)
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 get_cursor_pos_color(x=None, y=None, **ka): ''' x or y arg 优先 return [x,y],color ''' U, T, N, F = py.importUTNF() if not py.isint(x) and y == None: pos = x if x == None or y == None: pos = U.get_duplicated_kargs(ka, 'pos', 'xy') if not pos: pos = get_cursor_pos() else: pos = [x, y] pos = py.list(pos) if py.isint(x): pos[0] = x if py.isint(y): pos[1] = y import win32gui color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), *pos) if color < 256: color = 256 * 256 * color color = U.IntCustomRepr(color, repr=U.rgb_name(color)) return pos, color
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 bin(a,split=''): ''' bin(number, /) F.bin(1.0)=='0b00111111100000000000000000000000' # (大端) ''' import struct if py.isint(a): return py.bin(a) r='0b' if py.isfloat(a): r=r+split.join(py.bin(i).replace('0b', '').rjust(8, '0') for i in struct.pack('!f', a)) elif py.isbytes(a): r=r+split.join(py.bin(i).replace('0b', '').rjust(8, '0') for i in a) else: raise py.ArgumentUnsupported('#TODO type',a) 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 read_xlsx(file,sheet=0): ''' 加载一个8M多xlsx文件,很慢,''' import openpyxl if py.isinstance(file,openpyxl.workbook.workbook.Workbook): wb=file elif py.istr(file): wb = openpyxl.load_workbook(file)# 这句很耗时 else: raise py.ArgumentUnsupported(file) if py.isint(sheet): ws=wb[wb.sheetnames[sheet]] elif py.istr(sheet): ws=wb[sheet] else:raise py.ArgumentError('sheet is index or sheet_names') r=[] for row in ws.values:#<Worksheet "1 lemmas"> ri=[] for value in row: ri.append(value) r.append(ri) return r
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)
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 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)