Python check command output

Python: execute shell commands (and get the output) with the os package

This article is part of a two-part series related to running shell commands from within Python.

Execute shell commands using the os package

The most straightforward solution to running shell commands via Python is simply by using the system method of the os package. The os package “provides a portable way of using operating system dependent functionality.” The system method executes a string as a command in a subshell, which basically is an independent instance of the command processor of your operating system. For Windows, commands will be run using cmd.exe, for Linux this will be Bash, Mac will use Bash or Z shell.

The following code will open a subshell, run the command, and return the process exit code — a 0 (zero) if the command has run successfully, other numbers mean something has gone wrong (see Linux and Windows).

import os os.system('echo "Hello World!"')

Execute shell commands and get the output using the os package

Sometimes, you’re not only interested in running shell commands, but you’d also like to know what printed output is. The os package also has a solution for this: the popen method. This method opens a pipe into the command, which is used to transfer its output to a Python variable.

Читайте также:  Style css div background image

The following code will once again open a subshell and run the command, but instead of returning the process exit code, it will return the command output. If you ‘d like to remove the trailing nextline (\n), you can use the strip method

output_stream = os.popen('echo "Hello World!"') output_stream.read()
  • If the command passed to the shell generates errors, it will only return two single quotes.
  • If you would like to know if a command completed successfully, you can access the process exit code using the close method. Like this:
output_stream = os.popen('non-existing-command') output_stream.close()

The popen method of the os package uses the subprocess module. So instead of using popen, you might as well interface with the subprocess module directly. We discuss this in the next article.

Источник

How to Use Python Subprocess Check_output Method?

In this article, we will give a brief introduction of python subprocesses and discuss how to use subprocess check_output in python. Let’s start with knowing what a sub-process is in python. Subprocess is a python module that is used to run new codes by creating new processes. It allows the user to create a new application within the currently executing python program. When the user wants to execute an external program from a C or C++ program or any external program from a git repository, the python subprocess can merge those programs. Moreover, the user can also get input, output, exit codes, or error pipes using the python subprocess. Two parameters in the function call are passed; the first parameter refers to the program which the user wants to initialize, and the other argument refers to the file arguments.

There are many subprocess modules in python, for example, subprocess.run(), subprocess.Popen(), subprocess.call(), subprocess.check_call(), subprocess.check_output(), etc. Here we are going to enlighten what is the subprocess.check_output(), what its function is, and how it is used in a python program.

The syntax of subprocess.check_output()

Every python program has standard channels for the process or subprocess. These channels are started by call() and bound to the input and output of the parent program. In other words, the command of the output of the calling program cannot be captured. Hence, the check_output() subprocess module in python is used to capture the output of the calling program for later processing. The syntax of subprocess.check_output() is as follow:

subprocess . check_output ( args , * , stdin = None , stderr = None , shell = False , universal_newlines = False )

The ‘args’ argument of the subprocess.check_output refers to the command that is to be executed. Multiple commands can be passed to the ‘args’ argument as a string; however, they must be separated by a semicolon ‘;.’ The stdin argument refers to the value of the standard input stream that needs to be passed a pipe. The stdout argument refers to the value of the output generated from the standard output stream. The stderr argument refers to the value of error generated from the standard error stream.

The shell argument refers to the boolean parameter, which is executed through a new shell environment only when it is True. The last argument, universal_newlines is another boolean parameter. If the universal_newlines argument is True, then the file that contains stdout and stderr will open in universal newline mode. The output or the return of the subprocess.check_output() is the code of the command.

Here is an example to make you understand how the check_output() module captures the output of the calling program.

Example 1:

This simple example will produce the output code of the command.

calling_output = subprocess . check_output ( [ ‘ls’ , ‘-l’ ] )

Here is the output of the given an example:

Example 2:

This example will produce the output of the calling program.

print ( subprocess . check_output ( [ «echo» , «abc» ] ) )

Here is the output of the above code:

Example 3:

This example will demonstrate how external programs of any programming language like C, C++, Java, etc., are incorporated in a python program using subprocess in python and how check_output() will execute the output of those external programs.

class HelloWorld
{
public
static void main ( String args [ ] )
{
System . out . print ( «Print Hello_World from Java programing language» ) ;
}
}

Here is the python program that executes the above programs using subprocess in python

import subprocess
import os

def exeC ( ) :
a = subprocess . check_call ( «gcc Hello_World.c -o out1;./out1» , shell = True )
print ( «, output» , a )
def exeCpp ( ) :
data , temp = os . pipe ( )
os . write ( temp , bytes ( «5 10 \n » , «utf-8» ) ) ;
os . close ( temp )
s = subprocess . check_output ( «g++ HelloWorld.cpp -o out2;./out2» , stdin = data , shell = True )
print ( s. decode ( «utf-8» ) )
def exeJava ( ) :
s = subprocess . check_output ( «javac HelloWorld.java;java HelloWorld» , shell = True )
print ( s. decode ( «utf-8» ) )

if __name__ == «__main__» :
exeC ( )
exeCpp ( )
exeJava ( )

Here is the output of the above program:

Text Description automatically generated

Note: Even though the subprocess module in python is OS independent, these commands preferably need to be executed in the Linux environment. Moreover, the shell=True can become a security hazard if an untrusted input is combined, as defined in python documentation.

Conclusion:

This article is about the subprocess.check_output() module of the subprocess in python. Here we have a brief discussion of subprocesses in python and then explain the usage of the subprocess.check_output(). Let us have a quick recap of the article. The subprocess in python creates a new program to run a new code in it. It allows the user to create a new application within the currently executing python program. There are many modules of subprograms in python, and some of them are subprocess.call(), subprocess.Popen(), subprocess.check_call(), subprocess.check_output().

The subprocess.check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string. The stdin, stdout, and stderr provide the input, output, and error value, respectively, from the standard stream. The shell and universal_newlines are the Boolean parameters that only execute the commands when the value of the argument is True. The return code of the command is given as the output of the subprocess.check_ouput() function. A byte string is returned as output if the code is zero; else, CalledProcessError is being raised.

Источник

Модуль subprocess

Python 3 логотип

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

Рекомендуемым подходом к работе с подпроцессами является использование следующих вспомогательных функций для всех случаев, где они могут справиться. Для более сложных случаев может быть использован непосредственно интерфейс Popen.

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) — выполняет команду, описанную args. Ожидает завершения команды, а затем возвращает код возврата.

Аргументы, приведенные выше, являются лишь наиболее распространенными из них. Полная сигнатура функция в значительной степени такая же, как конструктор Popen. Аргумент timeout передается Popen.wait(). Если тайм-аут истекает, дочерний процесс будет убит, а затем будет поднято исключение TimeoutExpired.

 subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) - выполняет команду, описанную args. Ожидает завершения команды, а затем завершается, если код возврата 0, или поднимает исключение CalledProcessError, объект которого возвращает код завершения атрибутом returncode.

subprocess.check_output(args, *, input=None, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None) — выполняет команду и возвращает её вывод. Поднимает исключение CalledProcessError, если код возврата ненулевой.

Создание новых процессов и управление ими в данном модуле обрабатывается классом Popen. Он предлагает большую гибкость, так что разработчики могут справиться с менее распространенными случаями, не охваченными удобными функциями.

subprocess.DEVNULL — значение, которое может использоваться в качестве аргумента stdin, stdout или stderr. Означает, что будет использован специальный файл devnull.

subprocess.PIPE — значение, которое может использоваться в качестве аргумента stdin, stdout или stderr. Означает, что для дочернего процесса будет создан пайп.

subprocess.STDOUT — значение, которое может использоваться в качестве аргумента stderr. Означает, что поток ошибок будет перенаправлен в поток вывода.

Класс subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=()) — Выполняет программу в новом процессе. args – строка или последовательность аргументов программы. Обычно первым указывают исполняемую программу, а затем аргументы, но также ее можно указать в параметре executable.

Popen.poll() — если процесс завершил работу — вернёт код возврата, в ином случае None.

Popen.wait(timeout=None) — ожидает завершения работы процесса и возвращает код возврата. Если в течение timeout процесс не завершился, поднимется исключение TimeoutExpired (которое можно перехватить, после чего сделать ещё раз wait).

Этот метод может вызвать блокировку (зависание), если установлено stdout=PIPE или stderr=PIPE, и дочерний процесс генерирует большое количество данных в stdout и stderr. Использование communicate() позволит избежать этого.

Popen.communicate(input=None, timeout=None) — взаимодействовует с процессом: посылает данные, содержащиеся в input в stdin процесса, ожидает завершения работы процесса, возвращает кортеж данных потока вывода и ошибок. При этом в Popen необходимо задать значение PIPE для stdin (если вы хотите посылать в stdin), stdout, stderr (если вы хотите прочитать вывод дочернего процесса).

Если в течение timeout процесс не завершился, поднимется исключение TimeoutExpired (которое можно перехватить, после чего сделать ещё раз communicate, либо убить дочерний процесс).

Прочитанные данные буферизируются в память, поэтому не стоит применять этот метод в случае огромных выходных данных.

Popen.send_signal(signal) — посылает сигнал signal.

Popen.terminate() — останавливает дочерний процесс.

Popen.kill() — убивает дочерний процесс.

Для вставки кода на Python в комментарий заключайте его в теги

Источник

Оцените статью