• Linux
  • FreeBSD
  • Networking
  • Python
  • AWS
  • WebDev
  • About Us
Tech Tips and Tutorials
Menu
  • Linux
  • FreeBSD
  • Networking
  • Python
  • AWS
  • WebDev
  • About Us
Home  /  Python  /  How to run Shell commands in Python3

How to run Shell commands in Python3

Written by
Python Leave a Comment

Python allows you to run shell commands which you can use in your automation tasks and manage to start other serverside programs . Some of the useful python modules to execute shell commands are :

os.system(), os.popen() and subprocess.Popen 

You can immedeatley execute a shell command with the os.system command

import os
os.system('shell command')

os.popen module opens a pipe from command prompt . This pipe helps the command to send its output to another command . The output will be an open file and can be accessible from other programs .

Read(r) ::pipe = Popen('cmd', shell=True,bufsize=bufsize,stdout=PIPE).stdout 
Write(w)::pipe = Popen('cmd', shell=True, bufsize=bufsize, stdin=PIPE).stdin
import os
p = os.popen('df -h')
print(p.read())

It is better to assign the shell command to a variable and then use a seperate variable to interact with it . This will keep it neat as below:

Pythons subprocess modules replaces many features of the os modules. This module has the Popen class . This method allows the execution of the commands as child process. Some of the important subprocess.Popen methods are :

Popen.poll()	        Checks if the child process has terminated.
Popen.wait()	        Wait for the child process to terminate.
Popen.communicate()	Allows to interact with the process.
Popen.send_signal()	Sends a signal to the child process.
Popen.terminate()	Stops the child process.
Popen.kill()	        Kills a child process.

The available parameters for subpocess.Popen are :

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)

For eg : if you want to execute the command is shell , you can use the parameter shell=True

You might have noticed the object 0x7f.. in the last command , its better to assign the command to variable and execute in that way to keep it clean as below :

If you want to append the output of a command to a log file , check the link below :

subprocess.Popen Output

The poll() method returns the exit code if a command has finished running, or None if it’s still executing. For example:

the communicate() is another important method to communicate with the input and output of a command. You can use the ouput of one shell command to another one using this method .

If you want the ouput to be properly formatted just use the decode function before printing the output:

Share On
Share on Facebook
Share on Twitter
Share on Google+
Share on Whatsapp

 Previous Article How to redirect subprocess.Popen output to a file using in Python
Next Article   Error: /bin/sh: Syntax error: unexpected in Python3

Related Posts

  • Error: /bin/sh: Syntax error: unexpected in Python3

  • How to redirect subprocess.Popen output to a file using in Python

  • Compare two files and write only the differnce to another file in Python

Leave a Reply

Cancel reply

  • Popular Posts
  • Recent Posts
  • Linux Shell Scripts for System Administrators
  • Cacti 1.1.38 ERROR Opening .rrd No Such file or directory
  • Apache configuration for Cacti
  • How to create RAM disk in Ubuntu 18.04
  • Linux Shell Scripts for System Administrators
  • SOCKS PROXY
  • How to install XAMPP and access phpMyAdmin in MAC OS
  • How to increase the root volume in a Linux ec2 instance

Linux

  • Linux Shell Scripts for System Administrators
  • SOCKS PROXY
  • How to grep IP addresses from log files in Linux
  • How to empty or delete a large file in Linux

Categories

  • AWS (5)
  • FreeBSD (12)
  • Linux (29)
  • Networking (3)
  • Python (5)
  • Uncategorized (4)
  • WebDev (1)
  • Connect on Facebook
  • Connect on YouTube
© Copyright 2020.TechieNix. All Rights Reserved.
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Non-necessary

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.