Python Execution shell command

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.