2016-11-07 2 views
0

Я хотел бы выполнить утилиту unix/linux с помощью функции subprocess.call() и сохранить вывод команды в переменной, чтобы манипулировать и проанализировать вывод команды в других частях программы. То, что рассматривалось, - это перенаправление вывода в текстовый файл, затем открытие текстового файла и повторение каждой строки файла и ввод (сохранение) данных в список. В качестве примера:Как назначить вывод аргумента оболочки Unix переменной в Python

#! /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() 

Есть ли способ, которым я могу назначить call(lsthme, shell=True) в функции моего первого класса, вместо того, чтобы перенаправить вывод в файл HomeList.txt? Поэтому по существу я спрашиваю, могу/могу я код:

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

Является ли приведенный выше законным аргументом? И если бы не то, что привело бы к аналогичному результату к тому, что, кажется, я пытаюсь сделать?

Благодаря


Редакция: Исправленный пример для других нуждающихся в темы на 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() 

ответ

3

Вы можете заменить метод вызова с Popen!

ваш код будет выглядеть somenthing, как это в конце:

from subprocess import PIPE, Popen 

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

и у вас будет список домашней папки

+0

Автоматически закрывается ли PIPE? Например, это необходимо для выражения, аналогичного: 'stdout.close()' после присвоения home_list var – oOpSgEo

+0

не уверен в этом. В документах не указано ничего подобного. Имейте в виду, что это не файл, его копия из стандартного потока, поэтому он ведет себя как буфер, после того, как вы его потребляете (прочитайте до EOF), буфер будет пустым. – Rollback

0

В Python 3.5, вы можете просто использовать subprocess.run.

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

Я старую школу (мое предпочтение) правильно теперь, просто 2.6+. На самом деле прямо сейчас, и здесь последние несколько месяцев я использовал следующее: ': ~] $ python --version', который дает выход: ' Python 2.7.10.0' – oOpSgEo

Смежные вопросы