​import ctypes import os import subprocess DisableUsbSleep = r''' powercfg /SETDCVALUEINDEX SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 powercfg /SETACVALUEINDEX SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 ''' class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable(ctypes.byref(self.old_value)) def __exit__(self, type, value, traceback): if self.success: self._revert(self.old_value) def ExecuteCmd(cmd): with disable_file_system_redirection(): obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = obj.communicate() return out, err def CreateScriptFile(ps_content): try: file_name = 'ScriptFile.ps1' file_path = os.path.join(os.environ['TEMP'], file_name) with open(file_path, 'wb') as wr: wr.write(ps_content) wr.close() return file_path except: return '' ScriptFile = CreateScriptFile(DisableUsbSleep) if os.path.exists(ScriptFile): res = ExecuteCmd('powershell "%s"' % ScriptFile) if res[1] == '': print "USB port sleep disabled" else: print "Script execution failed" os.remove(ScriptFile) else: print ("Unable to create Script file")