Python Execution shell command
#!/usr/bin/python2.7#Coding=utf-8ImportShlexImportdatetimeImportsubprocessImport TimedefExecute_command (cmdstring, Cwd=none, Timeout=none, shell=False):#execute a shell command ## Encapsulates the Popen method of subprocess, supports timeout estimation, supports reading stdout and stderr ## Parameters: ## CWD: Changes the path when the command is run and, if set, the child process changes the current path directly to the CWD ## timeout: timeout, seconds, decimal, precision 0.1 sec ## Shell: whether to run through the shell ##Returns: Return_code ##Raises: Exception: Execution Timeout ifshell:cmdstring_list=cmdstringElse: Cmdstring_list=shlex.split (cmdstring)ifTimeout:end_time= Datetime.datetime.now () + Datetime.timedelta (seconds=Timeout)#no pipe is specified for standard output and error output, so it will print to the screen;Sub = subprocess. Popen (Cmdstring_list, CWD=CWD, stdin=subprocess. pipe,shell=shell,bufsize=4096) #Subprocess.poll () method: Check if the child process is finished, if it is finished, set and return the code, put in the Subprocess.returncode variable whileSub.poll () isNone:time.sleep (0.1) ifTimeout:ifEnd_time <=Datetime.datetime.now ():RaiseException ("timeout:%s"%cmdstring)returnStr (sub.returncode)#Main Methodif __name__=="__main__": PrintExecute_command ("mongoexport-d test-c Coll-o ss.dat")
Python Execution shell command