(ROOT, ROOT, ROOT)) os.system( 'limbo -t Loader -I%s/module %s/module/runt.m > %s/libinterp/loadermod.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -t Freetype -I%s/module %s/module/runt.m > %s/libinterp/freetypemod.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -t Bench -I%s/module %s/module/bench.m > %s/libinterp/benchmod.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -a -I%s/module %s/module/bench.m > %s/libinterp/bench.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -a -I%s/module %s/module/srvrunt.b >%s/emu/port/srv.h' % (ROOT, ROOT, ROOT)) os.system( 'limbo -t Srv -I%s/module %s/module/srvrunt.b >%s/emu/port/srvm.h' % (ROOT, ROOT, ROOT)) cmd = r'%s -o %s %s %s %s %s' % (CC, OUT, DEFINES, INCLUDES, FNAMES, LIBS) #print cmd #sys.exit() #os.system(cmd) import win32process, win32event hProcess, hThread, dwPid, dwTid = win32process.CreateProcess( None, cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO()) win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
def doCreate(): flags = win32con.CREATE_NO_WINDOW self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess( command, cmdline, None, None, 1, flags, env, path, StartupInfo)
def runExec(filename): handle = win32process.CreateProcess(u'yaz0enc.exe',' %s'%(r'"'+filename+r'"'),\ None,None,0,win32process.CREATE_NO_WINDOW,None,None,win32process.STARTUPINFO()) win32event.WaitForSingleObject(handle[0], -1)
def Spawn(self, arguments=[], environment=None, dir=None, path=None, exception_pipe=None): """Spawn the program. 'arguments' -- The sequence of arguments that should be passed to the executable. The first argument provided in this sequence will be 'argv[0]'; that is also the value used for the path to the executable. 'environment' -- If not 'None', a dictionary giving the environment that should be provided to the child. 'dir' -- If not 'None', the directory in which the child should begin execution. If 'None', the child will execute in the same directory as the parent. 'path' -- If not 'None', the path to the program to run. If 'None', 'arguments[0]' is used. 'exception_pipe' -- If not 'None', a pipe that the child can use to communicate an exception to the parent. This pipe is only used on UNIX systems. The write end of the pipe will be closed by this function. returns -- The PID of the child. Before creating the child, the parent will call 'self._InitializeParent'. On UNIX systems, the child will call 'self._InitializeChild' after 'fork', but before 'exec'. On non-UNIX systems, 'self._InitializeChild' will never be called. After creating the child, 'self._HandleChild' is called in the parent. This hook should be used to handle tasks that must be performed after the child is running. If the path to the program is absolute, or contains no separator characters, it is not modified. Otherwise the path to the program is relative, it is transformed into an absolute path using 'dir' as the base, or the current directory if 'dir' is not set.""" # Remember the directory in which the execution will occur. self.__dir = dir # The path to the executable is the first argument, if not # explicitly specified. if not path: path = arguments[0] # Normalize the path name. if os.path.isabs(path): # An absolute path. pass elif (os.sep in path or (os.altsep and os.altsep in path)): # A relative path name, like "./program". if dir: path = os.path.normpath(os.path.join(dir, path)) if not os.path.isabs(path): path = os.path.abspath(path) else: path = os.path.abspath(path) else: # A path with no directory separators. The program to # execute will be found by searching the PATH environment # variable. pass # Initialize the parent. startupinfo = self._InitializeParent() if sys.platform == "win32": # Compute the command line. The Windows API uses a single # string as the command line, rather than an array of # arguments. command_line = self.__CreateCommandLine(arguments) # Windows supports wide-characters in the environment, but # the Win32 extensions to Python require that all of the # entries in the environment be of the same type, # i.e,. that either all of them be of type StringType or # of type UnicodeType. Therefore, if we find any elements # that are Unicode strings, convert all of them to Unicode # strings. if environment is not None: # See if there any Unicode strings in the environment. uses_unicode = 0 for (k, v) in environment.iteritems(): if (isinstance(k, unicode) or isinstance(v, unicode)): uses_unicode = 1 break # If there are Unicode strings in the environment, # convert all of the key-value pairs to Unicode. if uses_unicode: new_environment = {} for (k, v) in environment.iteritems(): new_environment[unicode(k)] = unicode(v) environment = new_environment # Create the child process. self.__child \ = win32process.CreateProcess(path, command_line, None, None, 1, 0, environment, self.__dir, startupinfo)[0] else: # Fork. self.__child = os.fork() if self.__child == 0: try: # Close the read end of the pipe. if exception_pipe: os.close(exception_pipe[0]) # Initialize the child. self._InitializeChild() # Exec the program. if environment: os.execvpe(path, arguments, environment) else: os.execvp(path, arguments) except: if exception_pipe: # Get the exception information. exc_info = sys.exc_info() # Write it to the pipe. The traceback object # cannot be pickled, unfortunately, so we # cannot communicate that information. cPickle.dump(exc_info[:2], os.fdopen(exception_pipe[1], "w"), 1) # Exit without running cleanups. os._exit(1) # This code should never be reached. assert None # Nothing will be written to the exception pipe in the parent. if exception_pipe: os.close(exception_pipe[1]) # Let the parent take any actions required after creating the # child. self._HandleChild() return self.__child
def doCreate(): self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess( command, cmdline, None, None, 1, 0, env, path, StartupInfo)
try: os.system(shellCmd) except: pass app = 'soffice' display = '-nodisplay' logo = '-nologo' headview = '-headless' view = '-invisible' if sys.platform.startswith('win'): systemString = 'soffice -headless -invisible "-accept=socket,host=localhost,port=8100;urp;"' else: acceptString = '-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager' try: if sys.platform.startswith('win'): hProcess, hThread, processID, threadID = win32process.CreateProcess(None, systemString, None, None, 0, win32process.CREATE_NEW_PROCESS_GROUP, None, None, win32process.STARTUPINFO()) else: wizard = '-nofirststartwizard' args = ['soffice.bin', wizard, headview, acceptString] hProcess = popen2.Popen3(args) processID = hProcess.pid # cmd = 'netstat -anp | grep 8100' # os.system(cmd) except: cherrypy.log('Error in starting Open Office process...')
def run(self, cmdline): # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create pipes hStdin_r, self.hStdin_w = win32pipe.CreatePipe(sAttrs, 0) self.hStdout_r, hStdout_w = win32pipe.CreatePipe(sAttrs, 0) self.hStderr_r, hStderr_w = win32pipe.CreatePipe(sAttrs, 0) # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdInput = hStdin_r StartupInfo.hStdOutput = hStdout_w StartupInfo.hStdError = hStderr_w StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Mark doesn't support wShowWindow yet. # StartupInfo.dwFlags = StartupInfo.dwFlags | win32process.STARTF_USESHOWWINDOW # StartupInfo.wShowWindow = win32con.SW_HIDE # Create new output read handles and the input write handle. Set # the inheritance properties to FALSE. Otherwise, the child inherits # the these handles; resulting in non-closeable handles to the pipes # being created. pid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle( pid, self.hStdin_w, pid, 0, 0, # non-inheritable!! win32con.DUPLICATE_SAME_ACCESS) # Close the inhertible version of the handle win32file.CloseHandle(self.hStdin_w) self.hStdin_w = tmp tmp = win32api.DuplicateHandle( pid, self.hStdout_r, pid, 0, 0, # non-inheritable! win32con.DUPLICATE_SAME_ACCESS) # Close the inhertible version of the handle win32file.CloseHandle(self.hStdout_r) self.hStdout_r = tmp # start the process. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess( None, # program cmdline, # command line None, # process security attributes None, # thread attributes 1, # inherit handles, or USESTDHANDLES won't work. # creation flags. Don't access the console. 0, # Don't need anything here. # If you're in a GUI app, you should use # CREATE_NEW_CONSOLE here, or any subprocesses # might fall victim to the problem described in: # KB article: Q156755, cmd.exe requires # an NT console in order to perform redirection.. None, # no new environment None, # current directory (stay where we are) StartupInfo) # normally, we would save the pid etc. here... # Child is launched. Close the parents copy of those pipe handles # that only the child should have open. # You need to make sure that no handles to the write end of the # output pipe are maintained in this process or else the pipe will # not close when the child process exits and the ReadFile will hang. win32file.CloseHandle(hStderr_w) win32file.CloseHandle(hStdout_w) win32file.CloseHandle(hStdin_r) self.stdin = os.fdopen(msvcrt.open_osfhandle(self.hStdin_w, 0), "wb") self.stdin.write('hmmmmm\r\n') self.stdin.flush() self.stdin.close() self.stdout = os.fdopen(msvcrt.open_osfhandle(self.hStdout_r, 0), "rb") print("Read on stdout: ", repr(self.stdout.read())) self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb") print("Read on stderr: ", repr(self.stderr.read()))
#p = subprocess.Popen(pname, stdin=subprocess.PIPE,stdout=subprocess.PIPE) #result = p.communicate(input=source) #res = result[0].decode()[0:leng] #print(res) import win32api #日报软件启动 #win32api.ShellExecute(0, 'open', r'C:\Users\Administrator\Desktop\Debug\test.ece', '','',1) import os import win32process #os.startfile("C:/Users/Administrator/Desktop/Debug/test.exe") #win32process.CreateProcess('C:/Users/Administrator/Desktop/Debug/test.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW,None, None, win32process.STARTUPINFO()) import win32event handle = win32process.CreateProcess('C:/Users/Administrator/Desktop/Debug1/test.exe', "C:/Users/Administrator/Desktop/Debug1/test.exe 这是啥", None, None, 0, win32process.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO()) win32event.WaitForSingleObject(handle[0], -1) handle = win32process.CreateProcess('C:/Users/Administrator/Desktop/Debug1/test.exe', "C:/Users/Administrator/Desktop/Debug1/test.exe 结束了", None, None, 0, win32process.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO())
def __init__(self, path, host_pid, codepage=None, window_size_x=80, window_size_y=25, buffer_size_x=80, buffer_size_y=16000, local_echo=True, interact=False, **kwargs): """Initialize the console starts the child in it and reads the console periodically. Args: path (str): Child's executable with arguments. parent_pid (int): Parent (aka. host) process process-ID codepage (:obj:, optional): Output console code page. """ self.lastRead = 0 self.__bufferY = 0 self.lastReadData = "" self.totalRead = 0 self.__buffer = StringIO() self.__currentReadCo = win32console.PyCOORDType(0, 0) self.pipe = None self.connection = None self.consin = None self.consout = None self.local_echo = local_echo self.console_pid = os.getpid() self.host_pid = host_pid self.host_process = psutil.Process(host_pid) self.child_process = None self.child_pid = None self.enable_signal_chars = True logger.info( f'ConsoleReader started. location {os.path.abspath(__file__)}') if codepage is None: codepage = windll.kernel32.GetACP() try: logger.info("Setting console output code page to %s" % codepage) win32console.SetConsoleOutputCP(codepage) logger.info("Console output code page: %s" % ctypes.windll.kernel32.GetConsoleOutputCP()) except Exception as e: # pragma: no cover # I hope this code is unreachable... logger.error(e) try: self.create_connection(**kwargs) logger.info('Spawning %s' % path) try: self.initConsole() si = win32process.GetStartupInfo() self.__childProcess, _, self.child_pid, self.child_tid = win32process.CreateProcess( None, path, None, None, False, 0, None, None, si) self.child_process = psutil.Process(self.child_pid) logger.info( f'Child pid: {self.child_pid} Console pid: {self.console_pid}' ) except Exception: # pragma: no cover # I hope this code is unreachable... logger.error(traceback.format_exc()) return if interact: self.interact() self.interact() self.read_loop() except Exception: # pragma: no cover # I hope this code is unreachable... logger.error(traceback.format_exc()) finally: try: self.terminate_child() time.sleep(.01) self.send_to_host(self.readConsoleToCursor()) self.sendeof() time.sleep(.1) self.close_connection() logger.info('Console finished.') except Exception: # pragma: no cover # I hope this code is unreachable... logger.error(traceback.format_exc())
def checkSchedulerStart(errorHandler, name, isExisted): errorFile = "error.log" listFile = "schList.log" try: XPMode = False version = platform.platform() verReg = re.search('Windows-(\w+)-', version) if verReg != None: if verReg.group(1) == 'XP' or verReg.group(1) == '2003Server': XPMode = True if XPMode: filePath = os.getenv( 'windir') + os.sep + "Tasks" + os.sep + name + ".job" FileFunc.checkFileExist(errorHandler, filePath, isExisted) else: command = "cmd.exe /c chcp 437 | SCHTASKS /QUERY /TN " + "\"" + name + "\" 2>" + errorFile + " 1>" + listFile exePath = "C:\Windows\System32\cmd.exe" handle = win32process.CreateProcess(exePath, command, \ None , None , 0 ,win32process.CREATE_NEW_CONSOLE , None , None , \ win32process.STARTUPINFO()) win32event.WaitForSingleObject(handle[0], -1) time.sleep(1) if isExisted and os.path.getsize(errorFile) > 0: raise Exception("The job \"%s\" does not exist" % (name)) elif not isExisted and os.path.getsize(errorFile) == 0: disableFlag = False if os.path.exists(listFile): fList = codecs.open(listFile, 'r', encoding='utf8') for aLine in fList.readlines(): if aLine.find("Disabled") > -1: disableFlag = True break fList.close() if not disableFlag: raise Exception("The job \"%s\" exists" % (name)) #os.remove(errorFile) #os.remove(listFile) except Exception: if os.path.exists(errorFile): os.remove(errorFile) errorInfo = { Global.ERROR_CALLSTACK: traceback, Global.ERROR_MESSAGE: traceback.format_exc() } errorHandler.handler(errorInfo) return True
def TBStar_TBLogin(un, pw): try: global_TB.status = 1 if "TradeBlazer.exe" not in os.popen( 'tasklist /FI "IMAGENAME eq TradeBlazer.exe"').read(): #打开TB handle = win32process.CreateProcess( global_TB.path + 'TradeBlazer.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, global_TB.path, win32process.STARTUPINFO()) #打开TB,获得其句柄 time.sleep(21) Log('打开TB') #数据重置 win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'Button', '数据重置'), win32con.BM_CLICK, 1, 0) time.sleep(1) win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', '数据重置'), 0, 'Button', '重置(&R)'), win32con.BM_CLICK, 1, 0) time.sleep(1) win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', '确认'), 0, 'Button', '是(&Y)'), win32con.BM_CLICK, 1, 0) time.sleep(1) win32gui.PostMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', '提示'), 0, 'Button', '确定'), win32con.BM_CLICK, 1, 0) time.sleep(1) #登录框 win32gui.SendMessage( win32gui.FindWindowEx( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'ComboBox', None), 0, 'Edit', None), win32con.WM_SETTEXT, 0, un) time.sleep(1) win32gui.SendMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'Edit', None), win32con.WM_SETTEXT, 0, pw) time.sleep(1) win32gui.SendMessage( win32gui.FindWindowEx(win32gui.FindWindow('#32770', None), 0, 'Button', '登录(&L)'), win32con.BM_CLICK, 1, 0) ##global global_TB.status global_TB.status = 2 Log(str('登录柜台')) time.sleep(28) #取得TB句柄 win32gui.EnumWindows(handle_window, '交易开拓者') #time.sleep(2) #取得帐户列表数目 global_TB.Accounts = win32gui.SendMessage( win32gui.FindWindowEx( win32gui.FindWindowEx( win32gui.FindWindowEx( global_TB.TB_handle, win32gui.FindWindowEx(global_TB.TB_handle, 0, 'AfxControlBar110', None), 'AfxControlBar110', None), 0, None, '帐户管理'), 0, 'SysListView32', None), LVM_GETITEMCOUNT) global_TB.Trade = 0 except Exception as e: Log(str(e))
def create_process(self, path): _, _, process_id, _ = win32process.CreateProcess( None, path, None, None, 0, win32con.NORMAL_PRIORITY_CLASS, None, None, win32process.STARTUPINFO()) return process_id
def get_handle(app_info): return win32process.CreateProcess(app_info.path, '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO())
def create_process(process_path): return win32process.CreateProcess(None, process_path, None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO())
def InvokeCommand(self, ci): mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci handle = win32process.CreateProcess( os.path.join(win32api.GetSystemDirectory(), "cmd.exe"), '', None, None, 0, win32process.CREATE_NEW_CONSOLE, None, self.folder, win32process.STARTUPINFO())
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software") key = win32api.RegOpenKey(key, "Jabber") key = win32api.RegOpenKey(key, "Exodus") try: restart = win32api.RegOpenKey(key, "Restart") except: sys.exit(0) try: keys = [] for i in range(0, win32api.RegQueryInfoKey(restart)[0]): keys.append(win32api.RegEnumKey(restart, i)) for subkey in keys: skey = win32api.RegOpenKey(restart, subkey) cmdline = win32api.RegQueryValueEx(skey, "cmdline")[0] cwd = win32api.RegQueryValueEx(skey, "cwd")[0] print cmdline print cwd sui = win32process.STARTUPINFO() win32process.CreateProcess(None, cmdline, None, None, False, 0, None, cwd, sui) win32api.RegDeleteKey(restart, subkey) win32api.RegCloseKey(restart) win32api.RegDeleteKey(key, "Restart") except Exception, e: print traceback.print_exc() sys.exit(0) # not an error
def main(source, destination, job_name, version): extensions = set(('.pdb', '.dll', '.exe', '.ocx')) files_copied = 0 starttime = datetime.datetime.now() log("Start " + starttime.isoformat()) destdir = tempfile.mkdtemp() log("destination %s" % destdir) for root, dirs, files in os.walk(source): #print dirs for filename in (f for f in files if f[-4:] in extensions): pdb_dir = os.path.join(destdir, os.path.relpath(root, source)) try: os.makedirs(pdb_dir) except WindowsError as err: if err.winerror != 183: raise # print os.path.join(pdb_dir, filename) win32file.CreateHardLink(os.path.join(pdb_dir, filename), os.path.join(root, filename)) files_copied += 1 #except pywintypes.error as err: # if err.winerror != 183: #pywintypes.error (183, 'CreateHardLink', 'Cannot create a file when that file already exists.') for exclude in ('.git', '.svn', 'CVS', '.hg', '3rdParty', 'Python27', 'Python26'): if exclude in dirs: dirs.remove(exclude) log("%d files copied" % files_copied) startup = win32process.STARTUPINFO() startup.dwFlags += win32process.STARTF_USESTDHANDLES startup.hStdInput = win32file.INVALID_HANDLE_VALUE security_attributes = pywintypes.SECURITY_ATTRIBUTES() security_attributes.bInheritHandle = 1 log_path = os.path.join(destdir, "log") startup.hStdOutput = startup.hStdError = win32file.CreateFile( log_path, win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ, security_attributes, win32file.CREATE_ALWAYS, 0, None) win32file.WriteFile(startup.hStdOutput, 'log started\n') dtw_locations = ( os.path.join(os.environ.get('ProgramFiles', r'C:\Program Files (x86)'), 'Debugging Tools for Windows (x86)'), os.path.join(os.environ.get('ProgramFiles', r'C:\Program Files'), 'Debugging Tools for Windows (x64)'), os.path.join( os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)'), 'Debugging Tools for Windows (x86)'), os.path.join(os.environ.get('ProgramW6432', r'C:\Program Files'), 'Debugging Tools for Windows (x64)'), ) for dtw_location in dtw_locations: symstore = os.path.join(dtw_location, 'symstore.exe') if os.path.isfile(symstore): break else: raise Exception("Couldn't find symstore.exe in " + ' '.join(dtw_locations) + ". Is Debugging Tools for Windows installed?") (hProcess, hThread, processId, threadId) = win32process.CreateProcess( symstore, "symstore.exe add /r /f \"%s\" /s \"%s\" /t \"%s\" /v \"%s\"" % (destdir, destination, job_name, version), None, None, True, win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup) win32api.CloseHandle(hThread) # Don't need to wait here, but it doesn't take long, and we can remove the temp dir import win32event win32event.WaitForSingleObject(hProcess, win32event.INFINITE) exit_code = win32process.GetExitCodeProcess(hProcess) log("symstore exited with code " + str(exit_code)) win32api.CloseHandle(startup.hStdOutput) with file(log_path, "r") as log_file: for line in log_file: log("symstore: " + line.rstrip('\r\n')) import shutil shutil.rmtree(destdir) win32api.CloseHandle(hProcess) # print "\n".join(open(os.path.join(destdir, 'log'), 'r')) log("finish: %s" % datetime.datetime.now().isoformat()) log("elapsed time: %d seconds" % (datetime.datetime.now() - starttime).seconds) return exit_code
def startProcess(config): handle = win32process.CreateProcess(config['exePath'], '-console ' + config['console'] + ' -workdir ' + config['workdir'],\ None , None , 0 ,win32process. CREATE_NO_WINDOW , None , config['workdir'] ,win32process.STARTUPINFO()) return handle
def InvokeAndWait(path, cmdline="", timeout=10, tick=1.): """Invoke an application and wait for it to bring up a window. Args: path: full path to the executable to invoke cmdline: command line to pass to executable timeout: how long (in seconds) to wait before giving up tick: length of time to wait between checks Returns: A tuple of handles to the process and the application's window, or (None, None) if it timed out waiting for the process """ def EnumWindowProc(hwnd, ret): """Internal enumeration func, checks for visibility and proper PID.""" if win32gui.IsWindowVisible(hwnd): # don't bother even checking hidden wnds pid = win32process.GetWindowThreadProcessId(hwnd)[1] if pid == ret[0]: ret[1] = hwnd return 0 # 0 means stop enumeration return 1 # 1 means continue enumeration # We don't need to change anything about the startupinfo structure # (the default is quite sufficient) but we need to create it just the # same. sinfo = win32process.STARTUPINFO() proc = win32process.CreateProcess( path, # path to new process's executable cmdline, # application's command line None, # process security attributes (default) None, # thread security attributes (default) False, # inherit parent's handles 0, # creation flags None, # environment variables None, # directory sinfo) # default startup info # Create process returns (prochandle, pid, threadhandle, tid). At # some point we may care about the other members, but for now, all # we're after is the pid pid = proc[2] # Enumeration APIs can take an arbitrary integer, usually a pointer, # to be passed to the enumeration function. We'll pass a pointer to # a structure containing the PID we're looking for, and an empty out # parameter to hold the found window ID ret = [pid, None] tries_until_timeout = timeout/tick num_tries = 0 # Enumerate top-level windows, look for one with our PID while num_tries < tries_until_timeout and ret[1] is None: try: win32gui.EnumWindows(EnumWindowProc, ret) except pywintypes.error, e: # error 0 isn't an error, it just meant the enumeration was # terminated early if e[0]: raise e time.sleep(tick) num_tries += 1
def __call__(self): saAttr = win32security.SECURITY_ATTRIBUTES() saAttr.bInheritHandle = 1 self.hChildStdoutRd = win32pipe.CreateNamedPipe( self.stdoutPipeName, win32con.PIPE_ACCESS_INBOUND | win32con.FILE_FLAG_OVERLAPPED, # open mode win32con.PIPE_TYPE_BYTE, # pipe mode 1, # max instances WindowsShell.BUFFER_SIZE, # out buffer size WindowsShell.BUFFER_SIZE, # in buffer size 15, # timeout saAttr) hChildStdoutWr = win32file.CreateFile( self.stdoutPipeName, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr, win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 15) win32api.SetHandleInformation(self.hChildStdoutRd, win32con.HANDLE_FLAG_INHERIT, 0) self.hChildStderrRd = win32pipe.CreateNamedPipe( self.stderrPipeName, win32con.PIPE_ACCESS_INBOUND | win32con.FILE_FLAG_OVERLAPPED, # open mode win32con.PIPE_TYPE_BYTE, # pipe mode 1, # max instances WindowsShell.BUFFER_SIZE, # out buffer size WindowsShell.BUFFER_SIZE, # in buffer size 15, # timeout saAttr) hChildStderrWr = win32file.CreateFile( self.stderrPipeName, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr, win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 15) win32api.SetHandleInformation(self.hChildStderrRd, win32con.HANDLE_FLAG_INHERIT, 0) # Create a pipe for the child process's STDIN. This one is opened # in duplex mode so we can read from it too in order to detect when # the child closes their end of the pipe. self.hChildStdinWr = win32pipe.CreateNamedPipe( self.stdinPipeName, win32con.PIPE_ACCESS_DUPLEX | win32con.FILE_FLAG_OVERLAPPED, # open mode win32con.PIPE_TYPE_BYTE, # pipe mode 1, # max instances WindowsShell.BUFFER_SIZE, # out buffer size WindowsShell.BUFFER_SIZE, # in buffer size 15, # timeout... 0 gives a default 50 ms saAttr) hChildStdinRd = win32file.CreateFile( self.stdinPipeName, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr, win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED | win32con.FILE_FLAG_NO_BUFFERING, 15) win32api.SetHandleInformation(self.hChildStdinWr, win32con.HANDLE_FLAG_INHERIT, 0) # set the info structure for the new process. This is where # we tell the process to use the pipes for stdout/err/in. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdOutput = hChildStdoutWr StartupInfo.hStdError = hChildStderrWr StartupInfo.hStdInput = hChildStdinRd StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES flags = win32process.CREATE_UNICODE_ENVIRONMENT try: processHandle, threadHandle, dwPid, dwTid = win32process.CreateProcess( None, # name self.cmdline, # command line None, # process handle not inheritable None, # thread handle not inheritable True, # handles are inherited flags, # creation flags None, # NULL, use parent environment None, # current directory StartupInfo) # STARTUPINFO pointer except pywintypes.error as e: logger.exception('%s\n%s\n', self.cmdline, e.strerror) messageBox(f'{self.cmdline}\n{e.strerror}', mfError, (mfOKButton, )) return None win32file.CloseHandle(processHandle) win32file.CloseHandle(threadHandle) win32file.CloseHandle(hChildStderrWr) win32file.CloseHandle(hChildStdoutWr) win32file.CloseHandle(hChildStdinRd) self.stdin = os.fdopen(msvcrt.open_osfhandle(int(self.hChildStdinWr), 0), 'wb', buffering=0) self.stdout = os.fdopen(msvcrt.open_osfhandle(int(self.hChildStdoutRd), 0), 'rb', buffering=0) self.stderr = os.fdopen(msvcrt.open_osfhandle(int(self.hChildStderrRd), 0), 'rb', buffering=0) fds = WindowPipe(stdin=self.stdin, stdout=self.stdout, stderr=self.stderr) return fds
def __init__(self, cmd, login=None, hStdin=None, hStdout=None, hStderr=None, show=1, xy=None, xySize=None, desktop=None): """ Create a Windows process. cmd: command to run login: run as user 'Domain\nUser\nPassword' hStdin, hStdout, hStderr: handles for process I/O; default is caller's stdin, stdout & stderr show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...) xy: window offset (x, y) of upper left corner in pixels xySize: window size (width, height) in pixels desktop: lpDesktop - name of desktop e.g. 'winsta0\\default' None = inherit current desktop '' = create new desktop if necessary User calling login requires additional privileges: Act as part of the operating system [not needed on Windows XP] Increase quotas Replace a process level token Login string must EITHER be an administrator's account (ordinary user can't access current desktop - see Microsoft Q165194) OR use desktop='' to run another desktop invisibly (may be very slow to startup & finalize). """ si = win32process.STARTUPINFO() si.dwFlags = (win32con.STARTF_USESTDHANDLES ^ win32con.STARTF_USESHOWWINDOW) if hStdin is None: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdin if hStdout is None: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdout if hStderr is None: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStderr si.wShowWindow = show if xy is not None: si.dwX, si.dwY = xy si.dwFlags ^= win32con.STARTF_USEPOSITION if xySize is not None: si.dwXSize, si.dwYSize = xySize si.dwFlags ^= win32con.STARTF_USESIZE if desktop is not None: si.lpDesktop = desktop procArgs = ( None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32process.CREATE_NEW_CONSOLE, # dwCreationFlags None, # newEnvironment None, # currentDirectory si) # startupinfo if login is not None: hUser = logonUser(login) win32security.ImpersonateLoggedOnUser(hUser) procHandles = win32process.CreateProcessAsUser(hUser, *procArgs) win32security.RevertToSelf() else: procHandles = win32process.CreateProcess(*procArgs) self.hProcess, self.hThread, self.PId, self.TId = procHandles
def start(self, cmd_line, timeout=None, retry_interval=None, create_new_console=False, wait_for_idle=True): """ Starts the application giving in cmd_line """ # try to parse executable name and check it has correct bitness if '.exe' in cmd_line: exe_name = cmd_line.split('.exe')[0] + '.exe' _warn_incorrect_binary_bitness(exe_name) if timeout is None: timeout = Timings.app_start_timeout if retry_interval is None: retry_interval = Timings.app_start_retry start_info = win32process.STARTUPINFO() # we need to wrap the command line as it can be modified # by the function command_line = cmd_line # Actually create the process dwCreationFlags = 0 if create_new_console: dwCreationFlags = win32con.CREATE_NEW_CONSOLE try: (hProcess, hThread, dwProcessId, dwThreadId) = win32process.CreateProcess( None, # module name command_line, # command line None, # Process handle not inheritable. None, # Thread handle not inheritable. 0, # Set handle inheritance to FALSE. dwCreationFlags, # Creation flags. None, # Use parent's environment block. None, # Use parent's starting directory. start_info) # STARTUPINFO structure. except Exception as exc: # if it failed for some reason message = ('Could not create the process "%s"\n' 'Error returned by CreateProcess: %s') % (cmd_line, str(exc)) raise AppStartError(message) self.process = dwProcessId self.__warn_incorrect_bitness() def AppIdle(): "Return true when the application is ready to start" result = win32event.WaitForInputIdle(hProcess, int(timeout * 1000)) # wait completed successfully if result == 0: return True # the wait returned because it timed out if result == win32con.WAIT_TIMEOUT: return False return bool(self.windows_()) if wait_for_idle: # Wait until the application is ready after starting it try: WaitUntil(timeout, retry_interval, AppIdle) except TimeoutError: pass return self
def runTexconv(dds_name, gtx_name, swizzle): handle = win32process.CreateProcess(u'TexConv2.exe', ' -i \"%s\" -o \"%s\" -swizzle %d'%(dds_name , gtx_name , swizzle),\ None,None,0,win32process.CREATE_NO_WINDOW,None,None,win32process.STARTUPINFO()) win32event.WaitForSingleObject(handle[0], -1)
def StartProcess(self, command, arglist, detached=1, maxWait=20): """ Start a new process. @param command : the name of the command to be started. It can either be a full pathname or a command name to be found on the default path. @param arglist : is a list of the arguments to the command. @param detached : a flag indicating whether this process should be run detached or the process manager should wait for it to complete execution to return. @type command: string @type arglist: list of strings @type detached: integer """ cmdline = command for arg in arglist: arg = str(arg) if arg.find(" ") != -1: # # If there are spaces, quote the arg # arg = '"' + arg + '"' cmdline += " " + arg try: startup_info = win32process.STARTUPINFO() log.debug("Creating process: %s", cmdline) info = win32process.CreateProcess( None, # AppName cmdline, # Command line None, # Process security None, # Thread security 0, # Inherit handles? win32con.NORMAL_PRIORITY_CLASS | win32con.CREATE_NO_WINDOW, None, # New environment None, # Current directory startup_info) log.debug("Create process returns: %s", info) pHandle = info[0] self.processes.append(pHandle) self.threadid[pHandle] = info[3] if not detached: pHandle = info[0] wTime = 0 tIncr = 1 # We have to wait for it to finish exitCode = win32process.GetExitCodeProcess(pHandle) while exitCode == 259 and wTime < maxWait: exitCode = win32process.GetExitCodeProcess(pHandle) time.sleep(tIncr) wTime = wTime + tIncr else: # Gotta kill it, sigh self.TerminateProcess(pHandle) retval = exitCode else: retval = pHandle except win32process.error, e: log.exception("process creation failed: %s", e) retval = None
def startChild(self, args, env): '''Start the console process. startChild() starts the console process with arguments to command it to create the read child process. startChild() does not connect to console, it just creates it. The console creation depends on if the host process is running in a normal python process, or in a PyInstaller bundle. ''' # startupinfo for Windows' CreateProcess. si = win32process.GetStartupInfo() si.dwFlags = win32process.STARTF_USESHOWWINDOW if not self.interact_state: si.wShowWindow = win32con.SW_HIDE # collect arguments for console self.console_class_parameters.update({ 'console_reader_class': self.console_class_name, 'host_pid': self.host_pid, 'local_echo': self.echo, 'interact': self.interact_state, 'codepage': self.codepage }) console_class_parameters_kv_pairs = [ f'--{k}={v}' for k, v in self.console_class_parameters.items() if v is not None ] console_class_parameters_str = ' '.join( console_class_parameters_kv_pairs) args_str = join_args(args) console_args = f" {console_class_parameters_str} -- {args_str}" # set environment variables for the console # Deep copy needed to prevent cycle-to-cycle growth. See #31 for more details. environ = os.environ.copy() if getattr(sys, 'frozen', False): # pragma: no cover '''Runing in a PyInstaller bundle: Pyinstaller has no explicit python interpreter, so console-reader should be bundled also, and host should call it as a windows executable. This code cannot be covered during tests, because it runs only in bundled way. https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#using-sys-executable-and-sys-argv-0 https://github.com/pyinstaller/pyinstaller/issues/822 ''' if not hasattr(sys, '_MEIPASS'): raise Exception( '`sys.frozen` found, but `sys._MEIPASS` not. Only pyinstaller is supported.' ) dirname = os.path.dirname(sys.executable) console_executable = os.path.join(dirname, '..', 'wexpect', 'wexpect.exe') commandLine = f'"{console_executable}" {console_args}' else: '''Runing in a normal python process ''' dirname = os.path.dirname(os.path.abspath(__file__)) spath = [os.path.dirname(dirname)] pyargs = ['-m'] python_executable = sys.executable if self.coverage_console_reader: pyargs = ['-m', 'coverage', 'run', '--parallel-mode', '-m'] # add current location to PYTHONPATH environment variable to be able to start the child. python_path = environ.get('PYTHONPATH', '') spath = ';'.join(spath) environ['PYTHONPATH'] = f'{spath};{python_path}' child_class_initializator = f"wexpect {console_args}" pyargs = ' '.join(pyargs) commandLine = f'"{python_executable}" {pyargs} {child_class_initializator}' logger.info(f'Console starter command:{commandLine}') # start the console-reader _, _, self.console_pid, __otid = win32process.CreateProcess( None, commandLine, None, None, False, win32process.CREATE_NEW_CONSOLE, environ, self.cwd, si)
def doCreate(): for key in env.keys(): if type(env[key]) == type(u"string"): env[key] = env[key].encode('MBCS') self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess( command, cmdline, None, None, 1, win32process.CREATE_NO_WINDOW, env, path, StartupInfo)
print "%d files copied" % files_copied startup = win32process.STARTUPINFO() startup.dwFlags += win32process.STARTF_USESTDHANDLES startup.hStdInput = win32file.INVALID_HANDLE_VALUE security_attributes = pywintypes.SECURITY_ATTRIBUTES() security_attributes.bInheritHandle = 1 startup.hStdOutput = startup.hStdError = win32file.CreateFile( os.path.join(destdir, "log"), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ, security_attributes, win32file.CREATE_ALWAYS, 0, None) win32file.WriteFile(startup.hStdOutput, 'log started\n') (hProcess, hThread, processId, threadId) = win32process.CreateProcess( r"C:\Program Files (x86)\Debugging Tools for Windows (x86)\symstore.exe", "symstore.exe add /r /f \"%s\" /s C:\\symstore /t META" % destdir, None, None, True, win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup) win32api.CloseHandle(startup.hStdOutput) win32api.CloseHandle(hThread) # Don't need to wait here, but it doesn't take long, and we can remove the temp dir import win32event win32event.WaitForSingleObject(hProcess, win32event.INFINITE) print "symstore exited with code " + str( win32process.GetExitCodeProcess(hProcess)) import shutil #shutil.rmtree(destdir) win32api.CloseHandle(hProcess)
def startBackgroundProcess(self): """Method to start a process running in the background. """ with process_lock: # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create pipes for the process to write to hStdin_r, hStdin = win32pipe.CreatePipe(sAttrs, 0) hStdout = win32file.CreateFile( self.stdout, win32file.GENERIC_WRITE | win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, sAttrs, win32file.CREATE_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None) hStderr = win32file.CreateFile( self.stderr, win32file.GENERIC_WRITE | win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, sAttrs, win32file.CREATE_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None) try: # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdInput = hStdin_r StartupInfo.hStdOutput = hStdout StartupInfo.hStdError = hStderr StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Create new handles for the thread ends of the pipes. The duplicated handles will # have their inheritence properties set to false so that any children inheriting these # handles will not have non-closeable handles to the pipes pid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle(pid, hStdin, pid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(hStdin) hStdin = tmp # start the process, and close down the copies of the process handles # we have open after the process creation (no longer needed here) old_command = command = self.__quotePath(self.command) for arg in self.arguments: command = '%s %s' % (command, self.__quotePath(arg)) # Windows CreateProcess maximum lpCommandLine length is 32,768 # http://msdn.microsoft.com/en-us/library/ms682425%28VS.85%29.aspx if len(command) >= 32768: # pragma: no cover raise ValueError( "Command line length exceeded 32768 characters: %s..." % command[:1000]) dwCreationFlags = 0 if IS_PRE_WINDOWS_8: # pragma: no cover # In case PySys is itself running in a job, might need to explicitly breakaway from it so we can give # it its own, but only for old pre-windows 8/2012, which support nested jobs dwCreationFlags = dwCreationFlags | win32process.CREATE_BREAKAWAY_FROM_JOB if self.command.lower().endswith(('.bat', '.cmd')): # If we don't start suspended there's a slight race condition but due to some issues with # initially-suspended processes hanging (seen many years ago), to be safe, only bother to close the # race condition for shell scripts (which is the main use case for this anyway) dwCreationFlags = dwCreationFlags | win32con.CREATE_SUSPENDED self.__job = self._createParentJob() try: self.__hProcess, self.__hThread, self.pid, self.__tid = win32process.CreateProcess( None, command, None, None, 1, dwCreationFlags, self.environs, os.path.normpath(self.workingDir), StartupInfo) except pywintypes.error as e: raise ProcessError("Error creating process %s: %s" % (old_command, e)) try: if not self.disableKillingChildProcesses: win32job.AssignProcessToJobObject( self.__job, self.__hProcess) else: self.__job = None # pragma: no cover except Exception as e: # pragma: no cover # Shouldn't fail unless process already terminated (which can happen since # if we didn't use SUSPENDED there's an inherent race here) if win32process.GetExitCodeProcess( self.__hProcess) == win32con.STILL_ACTIVE: log.warning( 'Failed to associate process %s with new job: %s (this may prevent automatic cleanup of child processes)' % (self, e)) # force use of TerminateProcess not TerminateJobObject if this failed self.__job = None if (dwCreationFlags & win32con.CREATE_SUSPENDED) != 0: win32process.ResumeThread(self.__hThread) finally: win32file.CloseHandle(hStdin_r) win32file.CloseHandle(hStdout) win32file.CloseHandle(hStderr) # set the handle to the stdin of the process self.__stdin = hStdin
b = os.popen('mkdir nwdir', 'r', 1) # command -- 使用的命令。 # mode -- 模式权限可以是 'r'(默认) 或 'w'。 # bufsize -- 指明了文件需要的缓冲大小:0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。 win32api.ShellExecute(0, 'open', 'notepad.exe', '','',1) # ShellExecute(hwnd, op , file , params , dir , bShow ) # 其参数含义如下所示。 # · hwnd:父窗口的句柄,如果没有父窗口,则为0。 # · op:要进行的操作,为“open”、“print”或者为空。 # · file:要运行的程序,或者打开的脚本。 # · params:要向程序传递的参数,如果打开的为文件,则为空。 # · dir:程序初始化的目录。 # · bShow:是否显示窗口。0不显示,1,显示 win32api.ShellExecute(0, 'open', 'notepad.exe', '001.txt', '', 1) win32api.ShellExecute(0, 'open', 'http://www.python.org', '','',1)#打开网页 win32process.CreateProcess('c:\\windows\\notepad.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) # (4)使用模块subprocess # 说到底还是subprocess最为强大,能实现很多功能:调用shell命令,获取调用信息,监控调用过程,超时终止等,要求调用过程不阻塞,还能交互, # 【CreateProcess】接收一个字符串参数, # args shell命令,可以是字符串或者序列类型(如:list,元组) # bufsize 指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲 # stdin, stdout, stderr 分别表示程序的标准输入、输出、 # subprocess.PIPE 在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。 #subprocess.STDOUT 创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。 # preexec_fn 只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用 # close_sfs 在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。 # shell 同上 # cwd 用于设置子进程的当前目录 # env 用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。 # universal_newlines 不同系统的换行符不同,True -> 同意使用 \n # startupinfo 只在windows下有效,将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
import os import time import win32process import psutil handle = win32process.CreateProcess('p1.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) while True: time.sleep(10) try: p = psutil.Process(handle[2]) print(p.status) except: handle = win32process.CreateProcess('p1.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) print('restart p1') p = psutil.Process(handle[2]) print(p.status)