Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Script execute commands in Terminal

People also ask

How do I run a Python command in terminal?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

How do I run a Python command in terminal and output?

In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE , and returning just the stdout attribute. You can pass stderr=subprocess. STDOUT to ensure that error messages are included in the returned output.

Can Python run cmd commands?

Method 1 (CMD /K): Execute a command and then remain Now what if you want to execute multiple command prompt commands from Python? If that's the case, you can insert the '&' symbol (or other symbols, such as '&&' for instance) in between the commands.


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]

I prefer usage of subprocess module:

from subprocess import call
call(["ls", "-l"])

Reason is that if you want to pass some variable in the script this gives very easy way for example take the following part of the code

abc = a.c
call(["vim", abc])

  • Custom standard input for python subprocess

In fact any question on subprocess will be a good read

  • https://stackoverflow.com/questions/tagged/subprocess

import os
os.system("echo 'hello world'")

This should work. I do not know how to print the output into the python Shell.


You should also look into commands.getstatusoutput

This returns a tuple of length 2.. The first is the return integer ( 0 - when the commands is successful ) second is the whole output as will be shown in the terminal.

For ls

    import commands
    s=commands.getstatusoutput('ls')
    print s
    >> (0, 'file_1\nfile_2\nfile_3')
    s[1].split("\n")
    >> ['file_1', 'file_2', 'file_3']