在这篇文章中,我们将为您详细介绍在Python2.6中导入win32api错误的内容,并且讨论关于导入python包出错的相关问题。此外,我们还会涉及一些关于Django-PythonCopyfile
在这篇文章中,我们将为您详细介绍在Python 2.6中导入win32api错误的内容,并且讨论关于导入python包出错的相关问题。此外,我们还会涉及一些关于Django -Python Copyfile 使用 win32api 权限被拒绝、Python win32api 模块-CloseHandle() 实例源码、Python win32api 模块-error() 实例源码、Python win32api 模块-FindFiles() 实例源码的知识,以帮助您更全面地了解这个主题。
本文目录一览:- 在Python 2.6中导入win32api错误(导入python包出错)
- Django -Python Copyfile 使用 win32api 权限被拒绝
- Python win32api 模块-CloseHandle() 实例源码
- Python win32api 模块-error() 实例源码
- Python win32api 模块-FindFiles() 实例源码
在Python 2.6中导入win32api错误(导入python包出错)
在Windows OS(64位)下运行python26时.....我遇到了类似以下错误:
import win32api" error in Python 2.6: pywintypes26.dll
要么
pythoncom26.dll missingImportError: DLL load failed: The specified module could not be found.
我已经完成了python26的msi安装,所有dll都可以在C:\ Python26 \ Lib \ site-packages \
pywin32_system32下找到
答案1
小编典典将pywintypes26.dll和pythoncom26.dll从复制C:\Python26\Lib\site-packages\pywin32_system32
到C:\Python26\Lib\site-packages\win32
->解决问题后!
Django -Python Copyfile 使用 win32api 权限被拒绝
如何解决Django -Python Copyfile 使用 win32api 权限被拒绝?
我希望在服务器上实现一个副本,我在我的网络服务器的客户端 HTML 上单击一个按钮,服务器实现了服务器内特定文件从固定目的地到服务器内另一个目的地的副本本身。服务器是基于 Windows 的,所以我使用了 win32api copyFile 方法,但它显示了访问被拒绝的错误。我该如何解决这个问题?我已尝试为驱动器设置权限。似乎 Django 为此需要管理权限,但不确定。欢迎使用其他解决方案。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
Python win32api 模块-CloseHandle() 实例源码
Python win32api 模块,CloseHandle() 实例源码
我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用win32api.CloseHandle()。
def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1) except win32api.error, details: if details[0] != winerror.ERROR_NO_TOKEN: raise # attempt to open the process token,since no thread token # exists tok = win32security.OpenProcesstoken(win32api.GetCurrentProcess(), TOKEN_QUERY) sid, attr = win32security.GetTokeninformation(tok, TokenUser) win32api.CloseHandle(tok) name, dom, typ = win32security.LookupAccountSid(None, sid) return dom
def run_elevated(command, args, wait=True): """Run the given command as an elevated user and wait for it to return""" ret = 1 if command.find('' '') > -1: command = ''"'' + command + ''"'' if platform.system() == ''Windows'': import win32api import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon logging.debug(command + '' '' + args) process_info = ShellExecuteEx(nShow=win32con.SW_HIDE, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=''runas'', lpFile=command, lpParameters=args) if wait: win32event.WaitForSingleObject(process_info[''hProcess''], 600000) ret = win32process.GetExitCodeProcess(process_info[''hProcess'']) win32api.CloseHandle(process_info[''hProcess'']) else: ret = process_info else: logging.debug(''sudo '' + command + '' '' + args) ret = subprocess.call(''sudo '' + command + '' '' + args, shell=True) return ret
def subprocess_terminate( proc ) : try: proc.terminate() except AttributeError: print " no terminate method to Popen.." try: import signal os.kill( proc.pid , signal.SIGTERM) except AttributeError: print " no os.kill,using win32api.." try: import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess( PROCESS_TERMINATE, False, proc.pid) win32api.TerminateProcess(handle,-1) win32api.CloseHandle(handle) except ImportError: print " ERROR: Could not terminate process."
def testCleanup1(self): # We used to clobber all outstanding exceptions. def f1(invalidate): import win32event h = win32event.CreateEvent(None, 0, None) if invalidate: win32api.CloseHandle(int(h)) 1/0 # If we invalidated,then the object destruction code will attempt # to close an invalid handle. We don''t wan''t an exception in # this case def f2(invalidate): """ This function should throw an IOError. """ try: f1(invalidate) except ZeroDivisionError, exc: raise IOError("raise 2") self.assertRaises(IOError, f2, False) # Now do it again,but so the auto object destruction # actually fails. self.assertRaises(IOError, True)
def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), 1) except win32api.error as details: if details[0] != winerror.ERROR_NO_TOKEN: raise # attempt to open the process token, sid) return dom
def testCleanup1(self): # We used to clobber all outstanding exceptions. def f1(invalidate): import win32event h = win32event.CreateEvent(None,then the object destruction code will attempt # to close an invalid handle. We don''t wan''t an exception in # this case def f2(invalidate): """ This function should throw an IOError. """ try: f1(invalidate) except ZeroDivisionError as exc: raise IOError("raise 2") self.assertRaises(IOError, True)
def _closeStdin(self): if hasattr(self, "hChildStdinWr"): win32file.CloseHandle(self.hChildStdinWr) del self.hChildStdinWr self.closingStdin = False self.closedStdin = True
def closeStderr(self): if hasattr(self, "hChildStderrRd"): win32file.CloseHandle(self.hChildStderrRd) del self.hChildStderrRd self.closedStderr = True self.connectionLostNotify()
def closeStdout(self): if hasattr(self, "hChildStdoutRd"): win32file.CloseHandle(self.hChildStdoutRd) del self.hChildStdoutRd self.closedStdout = True self.connectionLostNotify()
def close(self): try: win32api.CloseHandle(self.pipe) except pywintypes.error: # You can''t close std handles...? pass
def writeConnectionLost(self): self.deactivate() try: win32api.CloseHandle(self.writePipe) except pywintypes.error: # OMG what pass self.lostCallback()
def _closeStdin(self): if hasattr(self, "hChildStdinWr"): win32file.CloseHandle(self.hChildStdinWr) del self.hChildStdinWr self.closingStdin = False self.closedStdin = True
def closeStderr(self): if hasattr(self, "hChildStderrRd"): win32file.CloseHandle(self.hChildStderrRd) del self.hChildStderrRd self.closedStderr = True self.connectionLostNotify()
def closeStdout(self): if hasattr(self, "hChildStdoutRd"): win32file.CloseHandle(self.hChildStdoutRd) del self.hChildStdoutRd self.closedStdout = True self.connectionLostNotify()
def close(self): try: win32api.CloseHandle(self.pipe) except pywintypes.error: # You can''t close std handles...? pass
def writeConnectionLost(self): self.deactivate() try: win32api.CloseHandle(self.writePipe) except pywintypes.error: # OMG what pass self.lostCallback()
def wait_for_elevated_process(process_info): if platform.system() == ''Windows'' and ''hProcess'' in process_info: import win32api import win32con import win32event import win32process win32event.WaitForSingleObject(process_info[''hProcess''], 600000) ret = win32process.GetExitCodeProcess(process_info[''hProcess'']) win32api.CloseHandle(process_info[''hProcess'']) return ret # pylint: enable=E0611,E0401 # pylint: disable=E1101
def __del__(self): if self.locked: self.release() win32api.CloseHandle(self.handle)
def killProcName(procname): # Change suggested by Dan Knierim,who found that this performed a # "refresh",allowing us to kill processes created since this was run # for the first time. try: win32pdhutil.GetPerformanceAttributes(''Process'',''ID Process'',procname) except: pass pids = win32pdhutil.FindPerformanceAttributesByName(procname) # If _my_ pid in there,remove it! try: pids.remove(win32api.GetCurrentProcessId()) except ValueError: pass if len(pids)==0: result = "Can''t find %s" % procname elif len(pids)>1: result = "Found too many %s''s - pids=`%s`" % (procname,pids) else: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE,pids[0]) win32api.TerminateProcess(handle,0) win32api.CloseHandle(handle) result = "" return result
def testCleanup2(self): # Cause an exception during object destruction. # The worst this does is cause an ".XXX undetected error (why=3)" # So avoiding that is the goal import win32event h = win32event.CreateEvent(None, None) # Close the handle underneath the object. win32api.CloseHandle(int(h)) # Object destructor runs with the implicit close failing h = None
def testCleanup3(self): # And again with a class - no __del__ import win32event class Test: def __init__(self): self.h = win32event.CreateEvent(None, None) win32api.CloseHandle(int(self.h)) t=Test() t = None
def _getInvalidHandleException(self): try: win32api.CloseHandle(1) except win32api.error, exc: return exc self.fail("Didn''t get invalid-handle exception.")
def testSimple(self): self.assertRaises(pywintypes.error, win32api.CloseHandle, 1)
def testFuncIndex(self): exc = self._getInvalidHandleException() self._testExceptionIndex(exc, 1, "CloseHandle")
def testUnpack(self): try: win32api.CloseHandle(1) self.fail("expected exception!") except win32api.error, exc: self.failUnlessEqual(exc.winerror, winerror.ERROR_INVALID_HANDLE) self.failUnlessEqual(exc.funcname, "CloseHandle") expected_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() self.failUnlessEqual(exc.strerror, expected_msg)
def testAsstr(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() # early on the result actually *was* a tuple - it must always look like one err_tuple = (winerror.ERROR_INVALID_HANDLE, ''CloseHandle'', err_msg) self.failUnlessEqual(str(exc), str(err_tuple))
def testAttributes(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() self.failUnlessEqual(exc.winerror, winerror.ERROR_INVALID_HANDLE) self.failUnlessEqual(exc.strerror, err_msg) self.failUnlessEqual(exc.funcname, ''CloseHandle'') # some tests for ''insane'' args.
def killProcName(procname): # Change suggested by Dan Knierim,0) win32api.CloseHandle(handle) result = "" return result
def testCleanup2(self): # Cause an exception during object destruction. # The worst this does is cause an ".XXX undetected error (why=3)" # So avoiding that is the goal import win32event h = win32event.CreateEvent(None, None) # Close the handle underneath the object. win32api.CloseHandle(int(h)) # Object destructor runs with the implicit close failing h = None
def testCleanup3(self): # And again with a class - no __del__ import win32event class Test: def __init__(self): self.h = win32event.CreateEvent(None, None) win32api.CloseHandle(int(self.h)) t=Test() t = None
def _getInvalidHandleException(self): try: win32api.CloseHandle(1) except win32api.error as exc: return exc self.fail("Didn''t get invalid-handle exception.")
def testSimple(self): self.assertRaises(pywintypes.error, 1)
def testFuncIndex(self): exc = self._getInvalidHandleException() self._testExceptionIndex(exc, "CloseHandle")
def testUnpack(self): try: win32api.CloseHandle(1) self.fail("expected exception!") except win32api.error as exc: self.failUnlessEqual(exc.winerror, expected_msg)
def testAsstr(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() # early on the result actually *was* a tuple - it must always look like one err_tuple = (winerror.ERROR_INVALID_HANDLE, str(err_tuple))
def testAttributes(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() self.failUnlessEqual(exc.winerror, ''CloseHandle'') # some tests for ''insane'' args.
def logout(self, session): """Delete session of it exists.""" if self.is_session_valid(session): sessionInfo = self.sessions[session] win32api.CloseHandle(sessionInfo[3]) del self.sessions[session]
def init_acls(): # A process that tries to read or write a SACL needs # to have and enable the SE_Security_NAME privilege. # And inorder to backup/restore,the SE_BACKUP_NAME and # SE_RESTORE_NAME privileges are needed. import win32api try: hnd = OpenProcesstoken(win32api.GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY) except win32api.error, exc: log.Log("Warning: unable to open Windows process token: %s" % exc, 5) return try: try: lpv = lambda priv: LookupPrivilegeValue(None, priv) # enable the SE_*_NAME privileges SecurityName = lpv(SE_Security_NAME) AdjustTokenPrivileges(hnd, [ (SecurityName, SE_PRIVILEGE_ENABLED), (lpv(SE_BACKUP_NAME), (lpv(SE_RESTORE_NAME), SE_PRIVILEGE_ENABLED) ]) except win32api.error, exc: log.Log("Warning: unable to enable SE_*_NAME privileges: %s" % exc, 5) return for name, enabled in GetTokeninformation(hnd, TokenPrivileges): if name == SecurityName and enabled: # Now we *may* access the SACL (sigh) ACL.flags |= SACL_Security_informatION break finally: win32api.CloseHandle(hnd)
def _readListViewItems(hwnd, column_index=0): # Allocate virtual memory inside target process pid = ctypes.create_string_buffer(4) p_pid = ctypes.addressof(pid) GetwindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd hProcHnd = OpenProcess(win32con.PROCESS_ALL_ACCESS, struct.unpack("i", pid)[0]) pLVI = VirtualAllocEx(hProcHnd, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) pBuffer = VirtualAllocEx(hProcHnd, win32con.PAGE_READWRITE) # Prepare an LVITEM record and write it to target process memory lvitem_str = struct.pack(''iiiiiiiii'', *[0, column_index, pBuffer, 0]) lvitem_buffer = ctypes.create_string_buffer(lvitem_str) copied = ctypes.create_string_buffer(4) p_copied = ctypes.addressof(copied) WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied) # iterate items in the SysListView32 control num_items = win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMCOUNT) item_texts = [] for item_index in range(num_items): win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMTEXT, item_index, pLVI) target_buff = ctypes.create_string_buffer(4096) ReadProcessMemory(hProcHnd, ctypes.addressof(target_buff), p_copied) item_texts.append(target_buff.value) VirtualFreeEx(hProcHnd, win32con.MEM_RELEASE) VirtualFreeEx(hProcHnd, win32con.MEM_RELEASE) win32api.CloseHandle(hProcHnd) return item_texts
def close(self): try: win32api.CloseHandle(self.pipe) except pywintypes.error: # You can''t close std handles...? pass
def writeConnectionLost(self): self.deactivate() try: win32api.CloseHandle(self.writePipe) except pywintypes.error: # OMG what pass self.lostCallback()
def killPID(pid, sig=None): """Kill the process with the given pid.""" try: if sig is None: from signal import SIGTERM sig = SIGTERM os.kill(pid, sig) except (AttributeError, ImportError): if win32api: handle = win32api.OpenProcess(1, pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle)
def clear_instance_check_event(self): ''''''Close handle created by CreateEvent'''''' if self.SICHECK_EVENT is not None: win32api.CloseHandle(self.SICHECK_EVENT)
def check_pids(curmir_incs): """Check PIDs in curmir markers to make sure rdiff-backup not running""" pid_re = re.compile("^PID\\s*([0-9]+)", re.I | re.M) def extract_pid(curmir_rp): """Return process ID from a current mirror marker,if any""" match = pid_re.search(curmir_rp.get_data()) if not match: return None else: return int(match.group(1)) def pid_running(pid): """True if we kNow if process with pid is currently running""" try: os.kill(pid, 0) except OSError, exc: if exc[0] == errno.ESRCH: return 0 else: log.Log("Warning: unable to check if PID %d still running" % (pid,), 2) except AttributeError: assert os.name == ''nt'' import win32api, win32con, pywintypes process = None try: process = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) except pywintypes.error, error: if error[0] == 87: return 0 else: msg = "Warning: unable to check if PID %d still running" log.Log(msg % pid, 2) if process: win32api.CloseHandle(process) return 1 return 0 return 1 for curmir_rp in curmir_incs: assert Globals.local_connection is curmir_rp.conn pid = extract_pid(curmir_rp) if pid is not None and pid_running(pid): log.Log.FatalError( """It appears that a prevIoUs rdiff-backup session with process id %d is still running. If two different rdiff-backup processes write the same repository simultaneously,data corruption will probably result. To proceed with regress anyway,rerun rdiff-backup with the --force option.""" % (pid,))
Python win32api 模块-error() 实例源码
Python win32api 模块,error() 实例源码
我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用win32api.error()。
def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1) except win32api.error, details: if details[0] != winerror.ERROR_NO_TOKEN: raise # attempt to open the process token,since no thread token # exists tok = win32security.OpenProcesstoken(win32api.GetCurrentProcess(), TOKEN_QUERY) sid, attr = win32security.GetTokeninformation(tok, TokenUser) win32api.CloseHandle(tok) name, dom, typ = win32security.LookupAccountSid(None, sid) return dom
def __init__ (self): wx.Frame.__init__ (self, None, title="Clipboard viewer", size=(250,150)) self.first = True self.nextWnd = None # Get native window handle of this wxWidget Frame. self.hwnd = self.GetHandle () # Set the WndProc to our function. self.oldWndProc = win32gui.SetwindowLong (self.hwnd, win32con.GWL_WNDPROC, self.MyWndProc) try: self.nextWnd = win32clipboard.SetClipboardViewer (self.hwnd) except win32api.error: if win32api.GetLastError () == 0: # information that there is no other window in chain pass else: raise
def MyWndProc (self, hWnd, msg, wParam, lParam): if msg == win32con.WM_CHANGECBCHAIN: self.OnChangeCBChain (msg, lParam) elif msg == win32con.WM_DRAWCLIPBOARD: self.OnDrawClipboard (msg, lParam) # Restore the old WndProc. Notice the use of win32api # instead of win32gui here. This is to avoid an error due to # not passing a callable object. if msg == win32con.WM_DESTROY: if self.nextWnd: win32clipboard.ChangeClipboardChain (self.hwnd, self.nextWnd) else: win32clipboard.ChangeClipboardChain (self.hwnd, 0) win32api.SetwindowLong (self.hwnd, win32con.GWL_WNDPROC, self.oldWndProc) # Pass all messages (in this case,yours may be different) on # to the original WndProc return win32gui.CallWindowProc (self.oldWndProc, hWnd, lParam)
def checkWork(self): finished = 0 fullDataRead = [] while 1: try: buffer, bytesToRead, result = win32pipe.PeekNamedPipe(self.pipe, 1) # finished = (result == -1) if not bytesToRead: break hr, data = win32file.ReadFile(self.pipe, None) fullDataRead.append(data) except win32api.error: finished = 1 break dataBuf = ''''.join(fullDataRead) if dataBuf: self.receivedCallback(dataBuf) if finished: self.cleanup() return len(dataBuf)
def RegisterCoreDLL(coredllName = None): """Registers the core DLL in the registry. If no params are passed,the name of the Python DLL used in the current process is used and registered. """ if coredllName is None: coredllName = win32api.GetmodulefileName(sys.dllhandle) # must exist! else: try: os.stat(coredllName) except os.error: print "Warning: Registering non-existant core DLL %s" % coredllName hKey = win32api.RegCreateKey(GetRootKey() , BuildDefaultPythonKey()) try: win32api.RegSetValue(hKey, "Dll", win32con.REG_SZ, coredllName) finally: win32api.RegCloseKey(hKey) # Lastly,setup the current version to point to me. win32api.RegSetValue(GetRootKey(), "Software\\\\Python\\\\PythonCore\\\\CurrentVersion", sys.winver)
def __init__(self, writePipe, lostCallback): self.disconnecting = False self.producer = None self.producerPaused = 0 self.streamingProducer = 0 self.outQueue = [] self.writePipe = writePipe self.lostCallback = lostCallback try: win32pipe.SetNamedPipeHandleState(writePipe, win32pipe.PIPE_NowAIT, None, None) except pywintypes.error: # Maybe it''s an invalid handle. Who kNows. pass
def RegisterPythonExe(exeFullPath, exeAlias = None, exeAppPath = None): """Register a .exe file that uses Python. Registers the .exe with the OS. This allows the specified .exe to be run from the command-line or start button without using the full path, and also to setup application specific path (ie,os.environ[''PATH'']). Currently the exeAppPath is not supported,so this function is general purpose,and not specific to Python at all. Later,exeAppPath may provide a reasonable default that is used. exeFullPath -- The full path to the .exe exeAlias = None -- An alias for the exe - if none,the base portion of the filename is used. exeAppPath -- Not supported. """ # Note - Dont work on win32s (but we dont care anymore!) if exeAppPath: raise error("Do not support exeAppPath argument currently") if exeAlias is None: exeAlias = os.path.basename(exeFullPath) win32api.RegSetValue(GetRootKey(), GetAppPathsKey() + "\\\\" + exeAlias, exeFullPath)
def RegisterModule(modName, modpath): """Register an explicit module in the registry. This forces the Python import mechanism to locate this module directly,without a sys.path search. Thus a registered module need not appear in sys.path at all. modName -- The name of the module,as used by import. modpath -- The full path and file name of the module. """ try: import os os.stat(modpath) except os.error: print "Warning: Registering non-existant module %s" % modpath win32api.RegSetValue(GetRootKey(), BuildDefaultPythonKey() + "\\\\Modules\\\\%s" % modName, win32con.REG_SZ, modpath)
def addcounter(self,object, counter, instance = None, inum=-1, machine=None): '''''' Adds a single counter path to the paths attribute. normally this will be called by a child class'' speciality functions, rather than being called directly by the user. (Though it isn''t hard to call manually,since almost everything is given a default) This method is only functional when the query is closed (or hasn''t yet been opened). This is to prevent conflict in multi-threaded query applications). e.g.: query.addcounter(''Memory'',''Available Bytes'') '''''' if not self.active: try: self.rawaddcounter(object, instance, inum, machine) return 0 except win32api.error: return -1 else: return -1
def collectdataslave(self,format = win32pdh.PDH_FMT_LONG): '''''' ### Not a public method Called only when the Query is kNown to be open,runs over the whole set of counters,appending results to the temp, returns the values as a list. '''''' try: win32pdh.CollectQueryData(self._base) temp = [] for counter in self.counters: ok = 0 try: if counter: temp.append(win32pdh.GetFormattedCounterValue(counter, format)[1]) ok = 1 except win32api.error: pass if not ok: temp.append(-1) # a better way to signal failure??? return temp except win32api.error: # will happen if,for instance,no counters are part of the query and we attempt to collect data for it. return [-1] * len(self.counters) # pickle functions
def open(self,*args,**namedargs): '''''' Explicitly open a query: When you are needing to make multiple calls to the same query, it is most efficient to open the query,run all of the calls, then close the query,instead of having the collectdata method automatically open and close the query each time it runs. There are currently no arguments to open. '''''' # do all the normal opening stuff,self._base is Now the query object BaseQuery.open(*(self,)+args, **namedargs) # should rewrite getinstpaths to take a single tuple paths = [] for tup in self.volatilecounters: paths[len(paths):] = self.getinstpaths(*tup) for path in paths: try: self.counters.append(win32pdh.AddCounter(self._base, path)) self.curpaths.append(path) # if we fail on the line above,this path won''t be in the table or the counters except win32api.error: pass # again,what to do with a malformed path???
def _GetServiceShortName(longName): # looks up a services name # from the display name # Thanks to Andy McKay for this code. access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYstem\\\\CurrentControlSet\\\\Services", 0, access) num = win32api.RegQueryInfoKey(hkey)[0] longName = longName.lower() # loop through number of subkeys for x in range(0, num): # find service name,open subkey svc = win32api.RegEnumKey(hkey, x) skey = win32api.RegOpenKey(hkey, svc, access) try: # find display name thisName = str(win32api.RegQueryValueEx(skey, "displayName")[0]) if thisName.lower() == longName: return svc except win32api.error: # in case there is no key called displayName pass return None # Open a service given either it''s long or short name.
def RemoveService(serviceName): try: import perfmon perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName) except (ImportError, win32api.error): pass hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS) try: hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS) win32service.DeleteService(hs) win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) import win32evtlogutil try: win32evtlogutil.RemoveSourceFromregistry(serviceName) except win32api.error: pass
def __FindSvcDeps(findName): if type(findName) is pywintypes.UnicodeType: findName = str(findName) dict = {} k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYstem\\\\CurrentControlSet\\\\Services") num = 0 while 1: try: svc = win32api.RegEnumKey(k, num) except win32api.error: break num = num + 1 sk = win32api.RegOpenKey(k, svc) try: deps, typ = win32api.RegQueryValueEx(sk, "DependOnService") except win32api.error: deps = () for dep in deps: dep = dep.lower() dep_on = dict.get(dep, []) dep_on.append(svc) dict[dep]=dep_on return __ResolveDeps(findName, dict)
def RestartService(serviceName, args = None, waitSeconds = 30, machine = None): "Stop the service,and then start it again (with some tolerance for allowing it to stop.)" try: StopService(serviceName, machine) except pywintypes.error, exc: # Allow only "service not running" error if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise # Give it a few goes,as the service may take time to stop for i in range(waitSeconds): try: StartService(serviceName, args, machine) break except pywintypes.error, exc: if exc.winerror!=winerror.ERROR_SERVICE_ALREADY_RUNNING: raise win32api.Sleep(1000) else: print "Gave up waiting for the old service to stop!"
def GetServiceClassstring(cls, argv = None): if argv is None: argv = sys.argv import pickle modName = pickle.whichmodule(cls, cls.__name__) if modName == ''__main__'': try: fname = win32api.GetFullPathName(argv[0]) path = os.path.split(fname)[0] # Eaaaahhhh - sometimes this will be a short filename,which causes # problems with 1.5.1 and the silly filename case rule. # Get the long name fname = os.path.join(path, win32api.FindFiles(fname)[0][8]) except win32api.error: raise error("Could not resolve the path name ''%s'' to a full path" % (argv[0])) modName = os.path.splitext(fname)[0] return modName + "." + cls.__name__
def _find_localserver_module(): import win32com.server path = win32com.server.__path__[0] baseName = "localserver" pyfile = os.path.join(path, baseName + ".py") try: os.stat(pyfile) except os.error: # See if we have a compiled extension if __debug__: ext = ".pyc" else: ext = ".pyo" pyfile = os.path.join(path, baseName + ext) try: os.stat(pyfile) except os.error: raise RuntimeError("Can not locate the Python module ''win32com.server.%s''" % baseName) return pyfile
def EnumKeys(root): index = 0 ret = [] while 1: try: item = win32api.RegEnumKey(root, index) except win32api.error: break try: # Note this doesn''t handle REG_EXPAND_SZ,but the implementation # here doesn''t need to - that is handled as the data is read. val = win32api.RegQueryValue(root, item) except win32api.error: val = "" # code using this assumes a string. ret.append((item, val)) index = index + 1 return ret
def GetDefaultProfileName(): import win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Windows Messaging Subsystem\\\\Profiles") try: return win32api.RegQueryValueEx(key, "DefaultProfile")[0] finally: key.Close() except win32api.error: return None # # Recursive dump of folders. #
def test(): import win32com.client oldcwd = os.getcwd() try: session = gencache.Ensuredispatch("MAPI.Session") try: session.logon(GetDefaultProfileName()) except pythoncom.com_error, details: print "Could not log on to MAPI:", details return except pythoncom.error: # no mapi.session - let''s try outlook app = gencache.Ensuredispatch("outlook.application") session = app.Session try: TestUser(session) TestAddress(session) DumpFolders(session) finally: session.logoff() # It appears Exchange will change the cwd on us :( os.chdir(oldcwd)
def _find_localserver_module(): import win32com.server path = win32com.server.__path__[0] baseName = "localserver" pyfile = os.path.join(path, baseName + ext) try: os.stat(pyfile) except os.error: raise RuntimeError("Can not locate the Python module ''win32com.server.%s''" % baseName) return pyfile
def EnumKeys(root): index = 0 ret = [] while 1: try: item = win32api.RegEnumKey(root, val)) index = index + 1 return ret
def test(): import win32com.client oldcwd = os.getcwd() try: session = gencache.Ensuredispatch("MAPI.Session") try: session.logon(GetDefaultProfileName()) except pythoncom.com_error, details return except pythoncom.error: # no mapi.session - let''s try outlook app = gencache.Ensuredispatch("outlook.application") session = app.Session try: TestUser(session) TestAddress(session) DumpFolders(session) finally: session.logoff() # It appears Exchange will change the cwd on us :( os.chdir(oldcwd)
def checkWork(self): finished = 0 fullDataRead = [] while 1: try: buffer, None) fullDataRead.append(data) except win32api.error: finished = 1 break dataBuf = ''''.join(fullDataRead) if dataBuf: self.receivedCallback(dataBuf) if finished: self.cleanup() return len(dataBuf)
def __init__(self, None) except pywintypes.error: # Maybe it''s an invalid handle. Who kNows. pass
def JobError(self, job, error): print ''Job Error'', error f = error.GetFile() print ''While downloading'', f.GetRemoteName() print ''To'', f.GetLocalName() print ''The following error happened:'' self._print_error(error) if f.GetRemoteName().endswith(''missing-favicon.ico''): print ''Changing to point to correct file'' f2 = f.QueryInterface(bits.IID_IBackgroundcopyFile2) favicon = ''http://www.python.org/favicon.ico'' print ''Changing RemoteName from'', f2.GetRemoteName(), ''to'', favicon f2.SetRemoteName(favicon) job.Resume() else: job.Cancel()
def __init__(self, module): self.module = module if hasattr(module, ''__file__''): fname = self.module.__file__ # Check for .pyc or .pyo or even .pys! if fname[-1] in [''O'',''o'',''C'',''c'', ''S'', ''s'']: fname = fname[:-1] try: fname = win32api.GetFullPathName(fname) except win32api.error: pass else: if module.__name__==''__main__'' and len(sys.argv)>0: fname = sys.argv[0] else: fname = "<UnkNown!>" SourceCodeContainer.__init__(self, fname)
def FindPackagePath(packageName, kNownFileName, searchPaths): """Find a package. Given a ni style package name,check the package is registered. First place looked is the registry for an existing entry. Then the searchPaths are searched. """ import regutil, os pathLook = regutil.GetRegisterednamedpath(packageName) if pathLook and IsPackageDir(pathLook, packageName, kNownFileName): return pathLook, None # The currently registered one is good. # Search down the search paths. for pathLook in searchPaths: if IsPackageDir(pathLook, kNownFileName): # Found it ret = os.path.abspath(pathLook) return ret, ret raise error("The package %s can not be located" % packageName)
def FindHelpPath(helpFile, helpDesc, searchPaths): # See if the current registry entry is OK import os, win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\\\Microsoft\\\\Windows\\\\Help", win32con.KEY_ALL_ACCESS) try: try: path = win32api.RegQueryValueEx(key, helpDesc)[0] if FileExists(os.path.join(path, helpFile)): return os.path.abspath(path) except win32api.error: pass # no registry entry. finally: key.Close() except win32api.error: pass for pathLook in searchPaths: if FileExists(os.path.join(pathLook, helpFile)): return os.path.abspath(pathLook) pathLook = os.path.join(pathLook, "Help") if FileExists(os.path.join( pathLook, helpFile)): return os.path.abspath(pathLook) raise error("The help file %s can not be located" % helpFile)
def FindAppPath(appName, searchPaths): """Find an application. First place looked is the registry for an existing entry. Then the searchPaths are searched. """ # Look in the first path. import regutil, string, os regPath = regutil.GetRegisterednamedpath(appName) if regPath: pathLook = regPath.split(";")[0] if regPath and FileExists(os.path.join(pathLook, kNownFileName)): return None # The currently registered one is good. # Search down the search paths. for pathLook in searchPaths: if FileExists(os.path.join(pathLook, kNownFileName)): # Found it return os.path.abspath(pathLook) raise error("The file %s can not be located for application %s" % (kNownFileName, appName))
def FindRegisterapp(appName, kNownFiles, searchPaths): """Find and Register a package. Assumes the core registry setup correctly. """ import regutil, string if type(kNownFiles)==type(''''): kNownFiles = [kNownFiles] paths=[] try: for kNownFile in kNownFiles: pathLook = FindAppPath(appName, kNownFile, searchPaths) if pathLook: paths.append(pathLook) except error, details: print "*** ", details return regutil.RegisterNamedpath(appName, ";".join(paths))
def dir(args): """dir directory_name ... Perform a directory listing on the remote device """ bRecurse = 0 try: opts, args = getopt.getopt(args, "r") except getopt.error, details: raise InvalidUsage(details) for o, v in opts: if o=="-r": bRecurse=1 for arg in args: print "Directory of WCE:%s" % arg files = BuildFileList(arg, bRecurse, _dirfilter, None) total_size=0 for full_name, info, rel_name in files: date_str = info[3].Format("%d-%b-%Y %H:%M") attr_string = " " if info[0] & win32con.FILE_ATTRIBUTE_DIRECTORY: attr_string = "<DIR>" print "%s %s %10d %s" % (date_str, attr_string, info[5], rel_name) total_size = total_size + info[5] print " " * 14 + "%3d files,%10d bytes" % (len(files), total_size)
def walk(arg, dirname, names): global numStamped vars, debug, descriptions = arg for name in names: for pat in g_patterns: if fnmatch.fnmatch(name, pat): # Handle the "_d" thing. pathname = os.path.join(dirname, name) base, ext = os.path.splitext(name) if base[-2:]==''_d'': name = base[:-2] + ext is_dll = ext.lower() != ".exe" if os.path.normcase(name) in descriptions: desc = descriptions[os.path.normcase(name)] try: verstamp.stamp(vars, pathname, desc, is_dll=is_dll) numStamped = numStamped + 1 except win32api.error, exc: print "Could not stamp", "Error", exc.winerror, "-", exc.strerror else: print ''WARNING: description not provided for:'', name # skip branding this - assume already branded or handled elsewhere # print "Stamped",pathname
def verify_request(self, sock, ca): # Do the sspi auth dance self.sa.reset() while 1: data = _get_msg(sock) if data is None: return False try: err, sec_buffer = self.sa.authorize(data) except sspi.error, details: print "Failed to authorize client:", details return False if err==0: break _send_msg(sock, sec_buffer[0].Buffer) return True
def DumpRegistry(root, level=0): # A recursive dump of the remote registry to test most functions. h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None) level_prefix = " " * level index = 0 # Enumerate values. while 1: try: name, data, typ = wincerapi.CeRegEnumValue(root, index) except win32api.error: break print "%s%s=%s" % (level_prefix, name, repr(str(data))) index = index+1 # Now enumerate all keys. index=0 while 1: try: name, klass = wincerapi.CeRegEnumKeyEx(root, index) except win32api.error: break print "%s%s\\\\" % (level_prefix, name) subkey = wincerapi.CeRegOpenKeyEx(root, name) DumpRegistry(subkey, level+1) index = index+1
def test1(self): # This used to leave a stale exception behind. def reg_operation(): hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name) x = 3/0 # or a statement like: raise ''error'' # do the test try: try: try: reg_operation() except: 1/0 # Force exception finally: win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name) except ZeroDivisionError: pass
def testSimpleFiles(self): fd, filename = tempfile.mkstemp() os.close(fd) os.unlink(filename) handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, win32con.CREATE_NEW, None) test_data = str2bytes("Hello\\0there") try: win32file.WriteFile(handle, test_data) handle.Close() # Try and open for read handle = win32file.CreateFile(filename, win32file.GENERIC_READ, win32con.OPEN_EXISTING, None) rc, data = win32file.ReadFile(handle, 1024) self.assertEquals(data, test_data) finally: handle.Close() try: os.unlink(filename) except os.error: pass # A simple test using normal read/write operations.
def _IOcpserverThread(self, handle, port, drop_overlapped_reference): overlapped = pywintypes.OVERLAPPED() win32pipe.ConnectNamedPipe(handle, overlapped) if drop_overlapped_reference: # Be naughty - the overlapped object is Now dead,but # GetQueuedCompletionStatus will still find it. Our check of # reference counting should catch that error. overlapped = None # even if we fail,be sure to close the handle; prevents hangs # on Vista 64... try: self.failUnlessRaises(RuntimeError, win32file.GetQueuedCompletionStatus, -1) finally: handle.Close() return result = win32file.GetQueuedCompletionStatus(port, -1) ol2 = result[-1] self.failUnless(ol2 is overlapped) data = win32file.ReadFile(handle, 512)[1] win32file.WriteFile(handle, data)
def testemptyDir(self): test_path = os.path.join(win32api.GetTempPath(), "win32file_test_directory") try: # Note: prevIoUsly used shutil.rmtree,but when looking for # reference count leaks,that function showed leaks! os.rmdir # doesn''t have that problem. os.rmdir(test_path) except os.error: pass os.mkdir(test_path) try: num = 0 for i in win32file.FindFilesIterator(os.path.join(test_path, "*")): num += 1 # Expecting "." and ".." only self.failUnlessEqual(2, num) finally: os.rmdir(test_path)
def testEncrypt(self): fname = tempfile.mktemp("win32file_test") f = open(fname, "wb") f.write(str2bytes("hello")) f.close() f = None try: try: win32file.EncryptFile(fname) except win32file.error, details: if details.winerror != winerror.ERROR_ACCESS_DENIED: raise print "It appears this is not NTFS - cant encrypt/decrypt" win32file.DecryptFile(fname) finally: if f is not None: f.close() os.unlink(fname)
def test_connect_without_payload(self): giveup_event = win32event.CreateEvent(None, None) t = threading.Thread(target=self.connect_thread_runner, args=(False, giveup_event)) t.start() time.sleep(0.1) s2 = socket.socket() ol = pywintypes.OVERLAPPED() s2.bind((''0.0.0.0'', 0)) # connectex requires the socket be bound beforehand try: win32file.ConnectEx(s2, self.addr, ol) except win32file.error, exc: win32event.SetEvent(giveup_event) if exc.winerror == 10022: # WSAEINVAL raise TestSkipped("ConnectEx is not available on this platform") raise # some error error we don''t expect. win32file.GetoverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() buff = win32file.AllocateReadBuffer(1024) win32file.WSARecv(s2, buff, 0) length = win32file.GetoverlappedResult(s2.fileno(), 1) self.response = buff[:length] self.assertEqual(self.response, str2bytes(''some expected response'')) t.join(5) self.failIf(t.isAlive(), "worker thread didn''t terminate")
def test_basics(self): s = socket.socket() e = win32event.CreateEvent(None, 1, None) win32file.WSAEventSelect(s, e, 0) self.assertEquals(win32file.WSAEnumNetworkEvents(s), {}) self.assertEquals(win32file.WSAEnumNetworkEvents(s, e), {}) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, 3) self.assertRaises(TypeError, "spam") self.assertRaises(TypeError, "spam", e) self.assertRaises(TypeError, "spam") f = open("NUL") h = win32file._get_osfhandle(f.fileno()) self.assertRaises(win32file.error, h) self.assertRaises(win32file.error, h) try: win32file.WSAEnumNetworkEvents(h) except win32file.error, e: self.assertEquals(e.winerror, win32file.WSAENOTSOCK) try: win32file.WSAEnumNetworkEvents(s, h) except win32file.error, e: # According to the docs it would seem reasonable that # this would fail with WSAEINVAL,but it doesn''t. self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
def CheckLoaderModule(dll_name): suffix = "" if is_debug_build: suffix = "_d" template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll") if not os.path.isfile(template): raise ConfigurationError( "Template loader ''%s'' does not exist" % (template,)) # We can''t do a simple "is newer" check,as the DLL is specific to the # Python version. So we check the date-time and size are identical, # and skip the copy in that case. src_stat = os.stat(template) try: dest_stat = os.stat(dll_name) except os.error: same = 0 else: same = src_stat[stat.ST_SIZE]==dest_stat[stat.ST_SIZE] and \\ src_stat[stat.ST_MTIME]==dest_stat[stat.ST_MTIME] if not same: log(2, "Updating %s->%s" % (template, dll_name)) shutil.copyfile(template, dll_name) shutil.copystat(template, dll_name) else: log(2, "%s is up to date." % (dll_name,))
def RegisterPythonExe(exeFullPath, exeFullPath)
def RegisterModule(modName, modpath)
def RegisterHelpFile(helpFile, helpPath, helpDesc = None, bCheckFile = 1): """Register a help file in the registry. Note that this used to support writing to the Windows Help key,however this is no longer done,as it seems to be incompatible. helpFile -- the base name of the help file. helpPath -- the path to the help file helpDesc -- A description for the help file. If None,the helpFile param is used. bCheckFile -- A flag indicating if the file existence should be checked. """ if helpDesc is None: helpDesc = helpFile fullHelpFile = os.path.join(helpPath, helpFile) try: if bCheckFile: os.stat(fullHelpFile) except os.error: raise ValueError("Help file does not exist") # Now register with Python itself. win32api.RegSetValue(GetRootKey(), BuildDefaultPythonKey() + "\\\\Help\\\\%s" % helpDesc, fullHelpFile)
def RegisterCoreDLL(coredllName = None): """Registers the core DLL in the registry. If no params are passed, sys.winver)
def addcounter(self, machine) return 0 except win32api.error: return -1 else: return -1
Python win32api 模块-FindFiles() 实例源码
Python win32api 模块,FindFiles() 实例源码
我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用win32api.FindFiles()。
def GetServiceClassstring(cls, argv = None): if argv is None: argv = sys.argv import pickle modName = pickle.whichmodule(cls, cls.__name__) if modName == ''__main__'': try: fname = win32api.GetFullPathName(argv[0]) path = os.path.split(fname)[0] # Eaaaahhhh - sometimes this will be a short filename,which causes # problems with 1.5.1 and the silly filename case rule. # Get the long name fname = os.path.join(path, win32api.FindFiles(fname)[0][8]) except win32api.error: raise error("Could not resolve the path name ''%s'' to a full path" % (argv[0])) modName = os.path.splitext(fname)[0] return modName + "." + cls.__name__
def GetServiceClassstring(cls, win32api.FindFiles(fname)[0][8]) except win32api.error: raise error("Could not resolve the path name ''%s'' to a full path" % (argv[0])) modName = os.path.splitext(fname)[0] return modName + "." + cls.__name__
def GetServiceClassstring(cls, win32api.FindFiles(fname)[0][8]) except win32api.error: raise error("Could not resolve the path name ''%s'' to a full path" % (argv[0])) modName = os.path.splitext(fname)[0] return modName + "." + cls.__name__
def FindFiles(spec, local=1): if local: return win32api.FindFiles(spec) else: return wincerapi.CeFindFiles(spec)
def BuildFileList(spec, local, recurse, filter, filter_args, recursed_path = ""): files = [] if isdir(spec, local): path = spec raw_spec = "*" else: path, raw_spec = os.path.split(spec) if recurse: # Need full scan,to get sub-direcetories. infos = FindFiles(os.path.join(path, "*"), local) else: infos = FindFiles(os.path.join(path, raw_spec), local) for info in infos: src_name = str(info[8]) full_src_name = os.path.join(path, src_name) if local: # Can''t do this for CE! full_src_name = win32api.GetFullPathName(full_src_name) if isdir(full_src_name, local) : if recurse and src_name not in [''.'',''..'']: new_spec = os.path.join(full_src_name, raw_spec) files = files + BuildFileList(new_spec, 1, os.path.join(recursed_path, src_name)) if fnmatch.fnmatch(src_name, raw_spec): rel_name = os.path.join(recursed_path, src_name) filter_data = filter( full_src_name, rel_name, info, filter_args ) if filter_data is not None: files.append( (full_src_name, filter_data) ) return files
def opendocumentFile(self, filename, bMakeVisible = 1): if filename is not None: try: path = os.path.split(filename)[0] # print "The editor is translating",`filename`,"to", filename = win32api.FindFiles(filename)[0][8] filename = os.path.join(path, filename) # print `filename` except (win32api.error, IndexError), details: pass # print "Couldnt get the full filename!",details return self._obj_.opendocumentFile(filename, bMakeVisible)
def opendocumentFile(self, IndexError) as details: pass # print "Couldnt get the full filename!", bMakeVisible)
def FindFiles(spec, local=1): if local: return win32api.FindFiles(spec) else: return wincerapi.CeFindFiles(spec)
def BuildFileList(spec, filter_data) ) return files
我们今天的关于在Python 2.6中导入win32api错误和导入python包出错的分享就到这里,谢谢您的阅读,如果想了解更多关于Django -Python Copyfile 使用 win32api 权限被拒绝、Python win32api 模块-CloseHandle() 实例源码、Python win32api 模块-error() 实例源码、Python win32api 模块-FindFiles() 实例源码的相关信息,可以在本站进行搜索。
本文标签: