我们在使用的时候也经常需要调用其他程序
例如:在app自动化时我们要获取手机的uuid和version,以及启用appium server
这时就用到了我们subprocess
库
库里面有很多的函数方法本篇博文就不做细细解释了
只说几个我们常用的方法
首先是popen类,这个类是将command放在新进程的子进程执行
"""
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. # 字符串类型或者序列(tuple\list)
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. # 一般使用subprocess.PIPE比较多,该模式的意思是打开通向标准流的管道
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. # 当args为字符串时,shell=True
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
"""
Popen().communicate
方法用于与执行的程序做交互,返回(stdout, stderr)元组
stdout为正常输出,stderr为错误输出
获取设备UUID和version 封装好的实例
import subprocess
class Command:
def __cmd_run(self, command):
try:
out, err = \
subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()
out = str(out, encoding="utf8").strip()
err = str(err, encoding="uft8").strip()
if err:
raise Exception("run command error {}".format(err))
except:
raise
else:
return out
def devices_and_version(self):
devices_uuid = self.__get_devices()
versions = self.__get_version()
res = list(zip(devices_uuid, versions))
return res
def __get_devices(self):
command = "adb devices"
res = self.__cmd_run(command)
if "\r\n" in res: # windows newline == \r\n
res = res.split("\r\n")
if "\n" in res: # linux newline == \n
res = res.split("\n")
res.remove("List of devices attached")
devices = []
for item in res:
if "device" in item:
device = item.split("\t")[0]
devices.append(device)
return devices
def __get_version(self):
uuids = self.__get_devices()
command = "adb -s {} shell getprop ro.build.version.release"
versions = []
for uuid in uuids:
version = self.__cmd_run(command.format(uuid))
versions.append(version)
return versions