0

I would like to execute a unix/linux utility via the subprocess.call() function and store the output of the command in a variable in order to manipulate and analyze the output of the command in other parts of the program. What was considering doing is redirecting a the output into a text file then opening the text file and iterating over each line of the file and inputting (storing) the data into a list. As an example:

#! /usr/bin/python

from subprocess import call

# This listHome.py program has been designed and created as a
# demonstration
# author:oOpSgEoW

class LstHome:

    def lsthome(self):
        # create the argument that will be passed to the call function
        lsthme = 'ls $HOME > HomeList.txt'
        # call the function
        call(lsthme, shell=True)

    def add_both(self):

        # create a list and a file object for the file
        lstOne = []
        fila = open('HomeList.txt', 'r')

        # iterate over each line of the file and store the 
        # data into the each index of the list 
        for line in fila:
            a = line.strip("\n")
            lstOne.append(a)

        # close the file
        fila.close()

        # return the list 
        return lstOne

class HomePrint():

    # intialize the class, pass the list as lstAlpha
    def __init__(self, lstAlpha=None):
        # to keep the bounds of the list, which will initialize
        # the list an empty list before the content of the list
        # being passed as an argument
        if lstAlpha is None:
            lstTwo = []
        self.lstTwo = lstAlpha
    def print_lst(self):
        for line1 in self.lstTwo:
            print(line1)

def main():

    # create an object out of the first class
    x = LstHome()

    # call the lsthome() function in 
    # order to execute the command givenper
    x.lsthome()

    # assign and create an object out of the HomePrint class
    # pass the output of the add_both() function from 
    # the LstHome() class
    y = HomePrint(x.add_both())
    y.print_lst()

    # an exit statement to the user
    print 'The $HOME directory of the user has been printed\ndone.'

main()

Is there a way I can assign the call(lsthme, shell=True) in my first class's function, instead of redirecting the output into the HomeList.txt file? So essentially I am asking can/could I code:

lsthme = 'ls $HOME'
holdVar = call(lsthme, shell=True)
print(holdVar)

Is the above a legal argument? And if not what would produce a similar result to what it seems I am trying to do?

Thanks


EDITED: Corrected example for others in need of topics on Python

#! /usr/bin/python

from subprocess import PIPE, Popen, call

# This listHome.py program has been designed and created to
# demonstrate a multi-class program that has a class receive
# an array/list as a parameter, and demonstrates interacting with a 
# Unix shell with a multi-class program
# author:oOpSgEoW

class LstHome:

    def lsthome(self):
        # create the argument that will be passed to the call function
        # Use the Popen function of subprocess
        lsthme = Popen("ls $HOME", shell=True, stdout=PIPE)

        # assign the function to lstOne 
        lstOne = lsthme.stdout.read().split('\n')
        # now that the data has been stored, the Pipe must be closed
        # NOTE: Generally speaking, what goes up must come down. What lives, must die. What opens must eventually close.
        lsthme.stdout.close()

        # return the lstOne object.
        return lstOne

class HomePrint():

    # intialize the class, pass the list as lstAlpha
    def __init__(self, lstAlpha=None):
        # to keep the bounds of the list, which will initialize
        # the list an empty list before the content of the list
        # being passed as an argument
        if lstAlpha is None:
            lstTwo = []
        self.lstTwo = lstAlpha

    def print_lst(self):
        for line1 in self.lstTwo:
        # NEVER PASS A NEWLINE RETURN TO THE CALL FUNCTION,
        # AT THE END OF AN ARGUMENT, just in case you wanted to
        # to take the output, or some of the output, and use as a 
        # command line input. For example:
        # if ".py" in line1:
        # line2 = line1.strip('\n')
        # mover = 'mv '
        # newmov = ' $HOME/Documents/Examples_In_Py/'
        # doTheMov = mover + line2 + newmov 
        # call(doTheMov, shell=True)
        print(line1)

def main():

    # create objects by performing class and functional abstraction
    x = LstHome()
    x.lsthome()
    # pass the list as an argument
    y = HomePrint(x.lsthome())
    y.print_lst()

    print 'The $HOME directory of the user has been printed\ndone.'

main()

2 Answers 2

3

You might replace the call method with the Popen!

your code will look somenthing like this at the end:

from subprocess import PIPE, Popen

res = Popen("ls $HOME",shell=True,  stdout=PIPE)
home_list = res.stdout.read().split('\n')

and you will have a list of the home folder

Sign up to request clarification or add additional context in comments.

2 Comments

Does the PIPE automatically close? For instance is it necessary for statement similar to: stdout.close() after the assignment to a home_list var
not sure about that. In the docs does not specify anything like that. Keep in mind that it is not a file, its a copy from the standard stream so it behaves like a buffer, after you consume it (read until EOF) the buffer will be empty
0

In Python 3.5, you can simply use subprocess.run.

import subprocess
output_bytes = subprocess.run("dir", shell=True, stdout=subprocess.PIPE).stdout

1 Comment

I'm old-schooling (my preference) right now, simply 2.6+. Actually right now, and here for the past few months I've been using the following, :~]$ python --version which yields an output of: Python 2.7.10.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.