subprocess модуль Python

  • Man /usr/share/doc/python2.6/html/library/subprocess.html

Модуль subprocess обеспечивает унифицированный интерфейса доступа к операционной системе. Модуль subprocess отвечает в языке Синтаксис Python за выполнение следующих действий: порождение новых процессов, соединение c потоками стандартного ввода, стандартного вывода, стандартного вывода сообщений об ошибках и получение кодов возврата от этих процессов.

Для запуска команд системы используется две функции subprocess.call() и subprocess.Popen(). Основное отличие этих функций между собой: функция subprocess.call() блокирует выполнение сценария до получения ответа, в то время как функция subprocess.Popen() - нет.

  • subprocess.call() - используется, если нужно просто запустить команду, а вывод от нее сохранять не требуется.
  • subprocess.Popen() - используется, если требуется захватить вывод команды
  • Пример №1. Использование subprocess.call
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess

def test1call():
    retcode=subprocess.call("du -hs $HOME/.viminfo", shell=True)
    if retcode == 0:
        print ("success")
    else:
        print ("failure")
  
def main():
    test1call()

if __name__ == '__main__':
    main()

class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

Аргументы:

  • bufsize if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered).
  • В Unix shell (по умолчанию False): выполняется os.execvp (). Если shell=True - аргументы представляют собой последовательность, первый пункт определяет командную строку, и любые дополнительные параметры будут рассматриваться в качестве дополнительного аргумента оболочки.
  • stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.
  • subprocess.PIPE. Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened.
  • subprocess.STDOUT. Special value that can be used as the stderr argument to Popen and indicates that standard error should go into the same handle as standard output.
  • Пример №1. Использование subprocess.Popen
#!/usr/bin/env python
import subprocess

def ping1(ipaddress="192.168.1.14"):
    p = subprocess.Popen("/bin/ping -c 2 %s" % ipaddress, shell=True,
                        stdout=subprocess.PIPE)
    out = p.stdout.read() #в переменной out находится вывод команды ping. Ниже идет обработка вывода команды ping.
    print out
    result = out.split()
    print result

if __name__ == '__main__':
    ping1()
output='dmesg | grep hda'

import subprocess
p1 = subprocess.Popen(["dmesg"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "hda"], stdin=p1.stdout, stdout=subprocess.PIPE)
PQ VPS сервера в 28+ странах.