问题
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
回答1:
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]
回答2:
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])
回答3:
- Custom standard input for python subprocess
In fact any question on subprocess will be a good read
- https://stackoverflow.com/questions/tagged/subprocess
回答4:
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']
回答5:
The os.popen() is pretty simply to use, but it has been deprecated since Python 2.6. You should use the subprocess module instead.
Read here: reading a os.popen(command) into a string
回答6:
import os
os.system("echo 'hello world'")
This should work. I do not know how to print the output into the python Shell.
回答7:
You could import the 'os' module and use it like this :
import os
os.system('#DesiredAction')
来源:https://stackoverflow.com/questions/3730964/python-script-execute-commands-in-terminal