#使用场景
需要开启两个服务,不想来回在终端开启,写python脚本,调用shell。
system 是阻塞的,最后更改成subprocess.Popen实现对应的功能。
!/usr/bin/python3
from future import print_function
import os
import subprocess
‘’’开启redis-server服务’’’
cmd = “redis-server”
‘’’os.system (‘redis-server’)’’’
p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
print(“redis-server”)
‘’’开启phhp服务’’’
cmd = “cd /dir-postion ;./think run”
p = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
print(“thinkphp server start”)
python脚本中执行shell命令的方法
用Python调用Shell命令有如下几种方式:
Subprocesses with accessible I/O streams
This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.
For a complete description of this module see the Python documentation.
Main API
run(…): Runs a command, waits for it to complete, then returns a
CompletedProcess instance.
Popen(…): A class for flexibly executing a command in a new process
Older API
call(…): Runs a command, waits for it to complete, then returns
the return code.
check_call(…): Same as call() but raises CalledProcessError()
if return code is not 0
check_output(…): Same as check_call() but returns the contents of
stdout instead of a return code
getoutput(…): Runs a command in the shell, waits for it to complete,
then returns the output
getstatusoutput(…): Runs a command in the shell, waits for it to complete,
then returns a (exitcode, output) tuple
class Popen(object):
“”” Execute a child program in a new process.
For a complete description of the arguments see the Python documentation.
Arguments:
args: A string, or a sequence of program arguments.
bufsize: supplied as the buffering argument to the open() function when
creating the stdin/stdout/stderr pipe file objects
executable: A replacement program to execute.
stdin, stdout and stderr: These specify the executed programs' standard
input, standard output and standard error file handles, respectively.
preexec_fn: (POSIX only) An object to be called in the child process
just before the child is executed.
close_fds: Controls closing or inheriting of file descriptors.
shell: If true, the command will be executed through the shell.
cwd: Sets the current directory before the child is executed.
env: Defines the environment variables for the new process.
text: If true, decode stdin, stdout and stderr using the given encoding
(if set) or the system default otherwise.
universal_newlines: Alias of text, provided for backwards compatibility.
startupinfo and creationflags (Windows only)
restore_signals (POSIX only)
start_new_session (POSIX only)
pass_fds (POSIX only)
encoding and errors: Text mode encoding and error handling to use for
file objects stdin, stdout and stderr.
Attributes:
stdin, stdout, stderr, pid, returncode
"""
下面是参数的意思:
name
参数 | 作用
-|-
args |一般是一个字符串,是要执行的shell命令内容|
bufsize |设置缓冲,负数表示系统默认缓冲,0表示无缓冲,正数表示自定义缓冲行数|
stdin |程序的标准输入句柄,NONE表示不进行重定向,继承父进程,PIPE表示创建管道|
stdout |程序的标准输出句柄,参数意义同上|
stderr |程序的标准错误句柄,参数意义同上,特殊,可以设置成STDOUT,表示与标准输出一致|
shell |为True时,表示将通过shell来执行|
cwd |用来设置当前子进程的目录|
env |设置环境变量,为NONE表示继承自父进程的|
第一种:
os.system(“ls”)
这个调用是同步进行的,程序需要阻塞并等待返回。
返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的。
第二种:
os.popen(command[,mode[,bufsize]])
popen方法通过p.read()获取终端输出,而且popen需要关闭close().当执行成功时,close()不返回任何值,失败时,close()返回系统返回值. 可见它获取返回值的方式和os.system不同。
第三种,使用commands模块,
根据你需要的不同,commands模块有三个方法可供选择。getstatusoutput, getoutput, getstatus。