Skip to content

How to a Run Bash Command in Python

If you need to run a bash command in your Python code, then you can do the following:

Option 1 – Using run() from subprocess Module

from subprocess import PIPE comp_process = subprocess.run("ls",stdout=PIPE, stderr=PIPE) print(comp_process.stdout)
Code language: Python (python)

Option 2 – Using Popen() from subprocess Module

from subprocess import PIPE process = subprocess.Popen("ls",stdout=PIPE, stderr=PIPE) output, error = process.communicate() print(output) process.kill
Code language: Python (python)

See also  How to Generate a Random Number/String in Terraform
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x