Fix Python – Python Script execute commands in Terminal [duplicate]

Question

Asked By – Ali

I read this somewhere a while ago but cant seem to find it. I am trying to find a command that will execute commands in the terminal and then output the result.

For example: the script will be:

command 'ls -l'

It will out the result of running that command in the terminal

Now we will see solution for issue: Python Script execute commands in Terminal [duplicate]


Answer

There are several ways to do this:

A simple way is using the os module:

import os
os.system("ls -l")

More complex things can be achieved with the subprocess module:
for example:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

This question is answered By – Uku Loskit

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0