A summary of two methods of executing the shell in Python

Source: Internet
Author: User
Tags pprint
First, execute the shell using Python's built-in commands module

Commands encapsulates Python's Os.popen (), uses the shell command string as its parameter, returns the result data of the command, and the state of the command execution;

The order is now obsolete and replaced by subprocess;

# coding=utf-8 "Created on November 22, 2013  @author: crazyant.net" Import commandsimport pprint  def cmd_exe (cmd_ String):  print "would exe Cmd,cmd:" +cmd_string  return Commands.getstatusoutput (cmd_string)  if __name__== "__main__":  pprint.pprint (Cmd_exe ("Ls-la"))

Second, use Python's latest subprocess module to execute the shell

Python has now abandoned os.system,os.spawn*,os.popen*,popen2.*,commands.* to execute commands in other languages, and Subprocesss is the recommended method;

Subprocess allows you to create many sub-processes that can be created to specify the input, output, and error output channels of the child and child processes, and to obtain the output and execution status after execution.

# coding=utf-8 "Created on November 22, 2013 @author: crazyant.net" Import shleximport datetimeimport subprocessimport time def execute_command (cmdstring, Cwd=none, Timeout=none, Shell=false): "" "Executes a shell command encapsulating Subprocess's Popen method, supporting time-out judgment, supporting  Read stdout and stderr parameters: CWD: Change the path when the command is run, if set, the child process will change the current path directly to CWD timeout: timeout, seconds, decimal, precision 0.1 sec Shell: Whether the shell is running Returns:return_code raises:exception: Execution Timeout "" "If shell:cmdstring_list = cmdstring else:cmdstring_list = SHL Ex.split (cmdstring) If timeout:end_time = Datetime.datetime.now () + Datetime.timedelta (seconds=timeout) #没有指定标准输出 And the wrong output of the pipe, 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, and place it in the Subprocess.returncode variable while Sub.poll () is None:time.sleep (0.1) If Timeout:if end_time <= datetime.datetime.now (): Raise Excepti On ("timeout:%s"%cmdstring) return str (sub.returncode) if __name__== "__main__": Print Execute_command ("ls") 

You can also specify stdin and stdout as a variable in popen, so that you can receive the output variable value directly.

Summarize

Executing the shell in Python is sometimes also necessary, such as using Python's threading mechanism to start different shell processes, currently subprocess is the official Python recommendation, and it supports the most features, which are recommended for everyone to use.

Well, the above is the whole content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.

Related Article

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.