os.system
仅仅在一个子终端运行command命令,而不能获取命令执行后的返回信息,而是返回command命令执行完毕后的退出状态。
system(command) -> exit_status
Execute the command (a string) in a subshell.
status = os.system('ls')
# status是退出状
os.popen
该方法不但执行命令还返回执行后的信息对象。打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
p=os.popen('ssh 10.3.16.121 ps aux | grep mysql')
x=p.read()
print x
p.close()
subprocess
import subprocess
subprocess.call (["cmd", "arg1", "arg2"],shell=True)
获取返回和输出:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line
retval = p.wait()
demo code:
def run_shell(command, cwd=None, env=None, quiet=False, universal_newlines=True):
"""
:param command:
:param cwd:
:param env:
:param quiet:
:param universal_newlines:
:return:
"""
# Use a shell for subcommands on Windows to get a PATH search.
use_shell = sys.platform.startswith("win")
if not use_shell and isinstance(command, str):
command = command.split(" ")
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
shell=use_shell,
cwd=cwd,
env=env,
universal_newlines=universal_newlines)
if not quiet:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
print(line.strip())
if isinstance(line, str):
output_array.append(line)
output = "".join(output_array)
else:
output = p.stdout.read()
p.wait()
p.stdout.close()
exit_code = p.returncode
if exit_code:
if isinstance(command, list):
command = " ".join(command)
error_message = "命令'{}'执行失败,请检查!".format(command)
print_failure(error_message)
sys.exit(1)
return output, exit_code
Comments 0