Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a shell command through Python

Tags:

python

shell

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

like image 810
hue Avatar asked May 07 '11 16:05

hue


People also ask

How do I run a shell command in Python using subprocess?

Python Subprocess Run Function run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.

Can Python use shell script?

You can run any shell command in Python just as it would be run with Bash. Given this bit of information, you can now create a Python version of ls . Just open up your favorite text editor in another terminal tab or window and place this in a file named pyls.py, and make it executable by using chmod +x pyls.py .


4 Answers

The subprocess module can be used for this purpose:

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

Replace x, y and z with the parameters to at.

like image 64
Sven Marnach Avatar answered Oct 10 '22 08:10

Sven Marnach


Alternatively, rather than using subprocess.call(), you could use Popen to capture the output of the command (rather than 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 useful to know. The same can be done with the stdin and stderr. Look at the documentation for more details.

like image 30
Michael Smith Avatar answered Oct 10 '22 08:10

Michael Smith


use search. already answered: How do I execute a program from python? os.system fails due to spaces in path

like image 34
MechanisM Avatar answered Oct 10 '22 09:10

MechanisM


subprocess.check_output appears to be the canonical convenience function in Python 2.4+ for executing a command and inspecting the output. It also raises an error if the command returns a non-zero value (indicating an error).

Like subprocess.call, check_output is a convenience wrapper around subprocess.Popen, so you may prefer using Popen directly. But convenience wrappers are ...convenient, in theory.

like image 34
Vynce Avatar answered Oct 10 '22 08:10

Vynce