def int_to_size_str(size,b1024=True,zero='0 B',less_than_zero='%s', ): '''Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes b1024 -- if True (default), use multiples of 1024 if False, use multiples of 1000 Returns: string test git ''' U,T,N,F=py.importUTNF() if py.istr(size) or py.isbyte(size): size=U.len(size) size=py.int(size) if size < 0: if py.callable(less_than_zero): return less_than_zero(size) if py.istr(less_than_zero): if '%' in less_than_zero: return less_than_zero%size if '{' in less_than_zero and '}' in less_than_zero: return less_than_zero.format(size) return less_than_zero if size==0:return zero # raise ValueError('number must be non-negative') multiple = 1024.0 if b1024 else 1000.0 #another if statement style if size<=multiple:return py.str(size)+' B' for suffix in SUFFIXES[multiple]: size /= multiple if size < multiple: return '{0:.3f} {1}'.format(size, suffix) raise ValueError('number too large')
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 run_as_user( cmd=r"notepad.exe C:\Windows\System32\drivers\etc\hosts", user=py. No('use current USER, no password window, privileg also can be elevated')): '''#带有 / - 的命令参数, 一定要三个引号。 三个以下都不行,示例: Win.runAs('cmd """ /k ping 192.168.43.1"""') Win.runAs('python """-c input(233)""" ') Win.runAs('ssh-keygen ') # 运行程序名中含有 - 没关系 Win.runAs('cmd """ -k echo 233 """') # -k 参数无效,只能/k Win.runAs('cmd """ /k whoami """',user='******') user='******' , ''' if user: if not user.strip().startswith('-Credential '): user = "******" % user else: user = '' # 不提供-Credential 参数,就好像右键 管理员运行一样,不要密码。是这个原因吗? ps = [ 'powershell.exe', # '-WindowStyle', # 'Hidden',# 在外层使用这个会将调用的python cmd窗口一起隐藏 ,要像下面一样在内层 '-ExecutionPolicy', 'Bypass', # 多参数不能写成一项,否则不允许使用与号(&)。& 运算符是为将来使用而保留的;请用双引号将与号引起来("&"),以将其作为字符串的一部分传递。: ParserError: (:) [], ParentContainsErrorRecordException '-command', r"""& {Start-Process powershell.exe %(user)s -WindowStyle Hidden -ArgumentList 'Start-Process %(cmd)s -Verb runAs'} """ % py.locals() ] U, T, N, F = py.importUTNF() return ps, U.cmd(ps)
def copy_with_src_dir_struct(abs_src_dir,abs_dst_dir,symlinks=False, ignore=None): import shutil U,T,N,F=py.importUTNF() if U.isWin():raise NotImplementedError() if abs_src_dir[-1] != '/':abs_src_dir+='/' if not F.exist(abs_src_dir):return F.exist(abs_src_dir) if abs_dst_dir[-1] != '/':abs_dst_dir+='/' if not F.exist(abs_dst_dir):return F.exist(abs_dst_dir) if not abs_dst_dir.endswith(abs_src_dir): # if abs_src_dir.startswith('') abs_dst_dir+=abs_src_dir abs_dst_dir=abs_dst_dir.replace('//','/') return shutil.copytree(abs_src_dir,abs_dst_dir, symlinks=symlinks,ignore=ignore,)
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 copy(src,dst,src_base='',skip=''): r''' src : sFilePath , list ,or \n strs dst:sPath ''' from shutil import copy as _copy if not py.istr(dst):raise py.ArgumentError('dst must be str') if py.istr(src): if '\n' in src: src=src.splitlines() return copy(src,dst) if src[-1] in ['/','\\']: src=F.ls(src,r=1) else: return _copy(src,dst) if not src_base: U,T,N,F=py.importUTNF() dl=U.unique(U.len(*src),ct=1) min=py.min(*dl) f=[i for i in src if py.len(i)==min][0] if f[-1] in ['/','\\']:f=f[:-1] # Path(f).absolute().parent.absolute().__str__() src_base=f[:py.len(T.sub_last(f.replace('\\','/'),'','/') )+1] src_base_len=py.len(src_base) print('src_base: %r'%src_base,'len(src)==%s'%py.len(src)) while dst[-1] not in ['/','\\']: dst=U.input('not dir! rewrite dst:',default=dst) if py.iterable(src): fns=[] skips=[] for i in src: if skip and skip in i: skips.append(i) continue # fn=getName(i) # if fn in fns: # fn=T.fileName(i) fn=i[src_base_len:] if fn[-1] in ['/','\\']: mkdir(dst+fn) else: _copy(i,dst+fn) fns.append(fn) if skips:return skips,fns return fns raise py.ArgumentUnsupported(src)
def open(file,mode='r',**ka): '''py.open( file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, ) ''' U,T,N,F=py.importUTNF() mode=U.get_duplicated_kargs(ka,'mode','mod','m',default=mode) if py.isfile(file): #if file.closed==False: return file elif py.istr(file): return py.open(file,mode=mode,**ka) else: raise py.ArgumentUnsupported(file,ka)
def win32_shellcopy(src, dest): """ Copy files and directories using Windows shell. :param src: Path or a list of paths to copy. Filename portion of a path (but not directory portion) can contain wildcards ``*`` and ``?``. :param dst: destination directory. :returns: ``True`` if the operation completed successfully, ``False`` if it was aborted by user (completed partially). :raises: ``WindowsError`` if anything went wrong. Typically, when source file was not found. .. seealso: `SHFileperation on MSDN <http://msdn.microsoft.com/en-us/library/windows/desktop/bb762164(v=vs.85).aspx>` """ from win32com.shell import shell, shellcon U, T, N, F = py.importUTNF() if py.istr(src): # in Py3 replace basestring with str src = F.abspath(src).replace('/', '\\') else: # iterable src = '\0'.join(F.abspath(path) for path in src) result, aborted = shell.SHFileOperation(( 0, shellcon.FO_COPY, src, F.abspath(dest).replace('/', '\\'), shellcon.FOF_NOCONFIRMMKDIR, # flags None, None)) if not aborted and result != 0: # Note: raising a WindowsError with correct error code is quite # difficult due to SHFileOperation historical idiosyncrasies. # Therefore we simply pass a message. raise WindowsError('SHFileOperation failed: 0x%08x' % result) return not aborted
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
#coding=utf-8 import sys,os,IPython if __name__.endswith('qgb.ipy'):from . import py#from . Attempted relative import in non-package else:import py U,T,N,F=py.importUTNF() gError=None # U.pln U.gError if not U.isipy():raise EnvironmentError g=get=gipy=U.isipy()#不能直接引用U.ipy,环境不确定 动态判断避免识别错误 g. gipy.autocall=2 if U.isWin(): gipy.editor='cmd /k start "" %s' % U.npp(get_cmd=True) try: from IPython.utils import py3compat # python 3.7 except:pass try: from IPython.utils.process import py3compat # python 3.5 except:pass py3compat.DEFAULT_ENCODING='gb18030' # default utf-8 if U.isLinux(): vim=U.where('vim') if vim: gipy.editor=vim else: gipy.editor=U.where('vi') gIn=gipy.user_ns['In'];gOut=gipy.user_ns['Out'] # version='.'.join([str(i) for i in IPython.version_info if py.isnum(i)]) #(5, 1, 0, '') 5.1.0 version=py.float('{0}.{1}{2}\n{3}'.format(*IPython.version_info).splitlines()[0]) # gipy.editor=U.npp()
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)