Methods to run application/OS commands using python



There are plenty of powerful modules comes along with python and even 3rd party modules are also available as the replacement of most of the OS and some application commands.

Though there are modules, any commands can be run using python with just OS and subprocess modules.

Here are the some examples that may be useful for you.

(1) When to use: When you just need to run a command and see it's output

    import os
  os.system('echo Hello')
  os.system('uname -a')


(2) When to use: When you just need to know an exit status of a command

     import os
  status = os.system('uname -a')

  print status

  if not status:
      print 'command ran success'
  else:
      print 'command returned failure'

(3) When to use: When you either need to run a command and see output or run a command and store the command output

   import commands
   commands.getoutput('uname -a')
   
   (or)

   output =  commands.getoutput('uname -a')

(4) When to use: When you want to run a command and see it status

   import commands
  commands.getstatusoutput('uname')[0]
  
  if the above command returns non zero, its failure. 


(5) When to use: When you want to store a command output as a variable in
      python

       import subprocess

    _uname = subprocess.Popen('uname -a',stdout=subprocess.PIPE,  shell=True).communicate()[0].rstrip('\n')
    

    print _uname

(6) When to use: When you want to run a command and proceed with the remaining program only if that command you ran was successful.

import subprocess
   subprocess.check_call('echo Hello')


Post a Comment

0 Comments