我們?cè)谑褂玫臅r(shí)候也經(jīng)常需要調(diào)用其他程序
例如:在app自動(dòng)化時(shí)我們要獲取手機(jī)的uuid和version,以及啟用appium server
這時(shí)就用到了我們subprocess
庫(kù)
庫(kù)里面有很多的函數(shù)方法本篇博文就不做細(xì)細(xì)解釋了
只說(shuō)幾個(gè)我們常用的方法
首先是popen類,這個(gè)類是將command放在新進(jìn)程的子進(jìn)程執(zhí)行
"""
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比較多,該模式的意思是打開(kāi)通向標(biāo)準(zhǔn)流的管道
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. # 當(dāng)args為字符串時(shí),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
方法用于與執(zhí)行的程序做交互,返回(stdout, stderr)元組
stdout為正常輸出,stderr為錯(cuò)誤輸出
獲取設(shè)備UUID和version 封裝好的實(shí)例
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
http://www.reibang.com/p/af5c6b1104d8 結(jié)合看更佳