UrbanPro
true

Learn Python Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Python in Unix

R
Rishi B.
03/04/2017 0 0

Python in Unix

How to run command on unix

Commands cannot be run directly on a unix server like we do in shell script.

SYNTAX:

  1. system("Command")
  2. check_output("Command", shell=True)
  3. call("Command", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

Diff:

1.Will print the output on screen, can store this in a variable but additional “0” will come on newline

  1. Output will not come on the screen. Can store it in a variable and print it. However, extra newline character come with it.
  2. It gives status of the command. Whether command was successfully executed or not.

e.g:

***********************

#!/usr/bin/python

import subprocess

os.system("ls –ltr /tmp”)

***********************

Using output from subprocess:

output=subprocess.check_output("command", shell=True)

Caution:the result stored in output is not Boolean so you can’t compare it in if statement. Below code will not work correctly. Also, the output is having change line character in the end.

Below Code will not work

***************************

#!/usr/bin/python

import subprocess

output=subprocess.check_output("grep -i noexec_user_stack_log /etc/system | wc -l", shell=True)

if output == 0:

    print("Correct")

else:

    print("Incorrect")

**************************

Correct code is:

*************************

#!/usr/bin/python

import subprocess

exit_code = subprocess.call("grep -i noexec_user_stack_log /etc/system | wc -l", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

if exit_code == 0:

    print("Correct")

else:

    print("Incorrect")

**************************

Making it simple by use of function:

from subprocess import PIPE, Popen

def cmdline(command):

    process = Popen(

        args=command,

        stdout=PIPE,

        shell=True

    )

    return process.communicate()[0]

print cmdline("cat /etc/host")

print cmdline('ls -ltr')

print cmdline('grep "max" /etc/system')

print cmdline('nslookup google.com') 

How to use variable in commands

Simply using a variable inside os.system will not work.

e.g:

*******************

#!/usr/bin/python
import os,sys
FILE=sys.argv[1]
os.system("ls -ltr /tmp")
os.system('chmod 750 /tmp/%(FILE)s'  % locals())

******************

How to assign unix command output to a variable and use it

When we store output from subprocess.check_output in a variable, it also stores newline character with the output. We need to remove it first then we can add any string or variable after that to print in same line.

*******************

#!/usr/bin/python

import subprocess,os,sys

SERVER=subprocess.check_output("hostname", shell=True)

LUN_ID=sys.argv[1]

cmd="zp{}".format(SERVER).strip()

cmd="{}_zpool_fs {}".format(cmd,LUN_ID)

print cmd

*******************

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

Visualize your python code
Hi All, Many developers in the beginning of their career want to visualize how their code is working and the program flow. You can use the following link to visualize your python code. http://www.pythontutor.com/visualize.html#mode=edit ...

Build an interactive Dictionary using Python 3.x
I have downloaded a 5MB data base consisting of words and their meanings in a json file . I want to write a python progrsm which will ask the user to enter a word and then the program will search through...
B

Biswanath Banerjee

0 0
0

Python - Solving Ordinary Differential Equations - Predator Prey Model aka Lotka Volterra Equations
This is an assignment in Python, I contributed to a numerical Python MOOC from George Washington University. The link to this assignment on github is here. The Lotka–Volterra equations, also...
S

Sri Vallabha Deevi

0 0
1

Top Programming Languages 2017: Every Beginner Should Learn
Every year a plethora of job opportunities are being created for skilled programmers. So if you are thinking of honing your coding skills it is really a bright idea. But with so many programming languages...

Python- Basic Concepts part 2
1. Other Numerical Operations a. Exponentiation Besides addition, subtraction, multiplication, and division, Python also supports exponentiation, which is the raising of one number to the power of...
X

Looking for Python Training Classes?

The best tutors for Python Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Python Training with the Best Tutors

The best Tutors for Python Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more