Summary of two methods for performing shell in python

  • 2020-05-19 05:07:50
  • OfStack

1. Use the python built-in commands module to execute shell

commands encapsulates os.popen () of Python, takes the SHELL command string as its argument, and returns the result data of the command and the status of its execution.

The order has now been scrapped and replaced by the subprocess;


# coding=utf-8
'''
Created on 2013 years 11 month 22 day 
 
@author: crazyant.net
'''
import commands
import pprint
 
def cmd_exe(cmd_String):
  print "will exe cmd,cmd:"+cmd_String
  return commands.getstatusoutput(cmd_String)
 
if __name__=="__main__":
  pprint.pprint(cmd_exe("ls -la"))

2. Use python's latest subprocess module to execute shell

Python has currently disused os.system, os.spawn *, os.popen *, popen2.*, commands.* to execute commands in other languages, subprocesss is the recommended method;

subprocess allows you to create many child processes, specify child processes and their input, output, and error output channels, and obtain output and execution status after execution.


# coding=utf-8
'''
Created on 2013 years 11 month 22 day 
 
@author: crazyant.net
'''
import shlex
import datetime
import subprocess
import time
 
def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
  """ perform 1 a SHELL The command 
       Encapsulates the subprocess the Popen methods ,  Support timeout judgment, support read stdout and stderr
       parameter :
    cwd:  Change the path when you run the command. If it is set, the child process will change the current path first cwd
    timeout:  Timeout time, seconds, support decimal, precision 0.1 seconds 
    shell:  Whether through shell run 
  Returns: return_code
  Raises: Exception:  timeouts 
  """
  if shell:
    cmdstring_list = cmdstring
  else:
    cmdstring_list = shlex.split(cmdstring)
  if timeout:
    end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
  
  # There is no pipe to specify standard output and error output, so it is printed to the screen; 
  sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
  
  #subprocess.poll() Method: check whether the child process is finished, if so, set and return the code, put subprocess.returncode variable  
  while sub.poll() is None:
    time.sleep(0.1)
    if timeout:
      if end_time <= datetime.datetime.now():
        raise Exception("Timeout : %s"%cmdstring)
      
  return str(sub.returncode)
 
if __name__=="__main__":
  print execute_command("ls")

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

conclusion

It is sometimes necessary to execute SHELL in python, for example, to use the threading mechanism of Python to start different shell processes. Currently, subprocess is officially recommended by Python, and it has the most supported functions, so it is recommended to use it.

Well, the above is the entire content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: