How to execute shell command through Python

I am new to Python programming. I want to execute the shell command "at" from a Python program. Can any python guru help me? Thanks in advance.

+6
source share
4 answers

For this purpose, you can use the subprocess module:

 import subprocess retcode = subprocess.call(["at", "x", "y", "z"]) 

Replace x , y and z at .

+8
source

Alternatively, instead of using subprocess.call (), you can use Popen to capture the output of the command (and not the return code).

 import subprocess process = subprocess.Popen(['at','x','y','z'], stdout=subprocess.PIPE).communicate()[0] 

This may not be relevant to the at command, but it is good to know. The same can be done with stdin and stderr. See more details.

+4
source

subprocess.check_output seems to be the canonical convenience function in Python 2.4+ to execute a command and verify output. It also throws an error if the command returns a nonzero value (indicating the error).

Like subprocess.call , check_output is a convenient wrapper around subprocess.Popen , so you can use Popen directly. But convenient wrappers ... are convenient, theoretically.

+1
source

Source: https://habr.com/ru/post/887521/


All Articles