本文整理汇总了Python中uiautomator.Device.screenshot方法的典型用法代码示例。如果您正苦于以下问题:Python Device.screenshot方法的具体用法?Python Device.screenshot怎么用?Python Device.screenshot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类uiautomator.Device
的用法示例。
在下文中一共展示了Device.screenshot方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Mobile
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
#.........这里部分代码省略.........
return obj.scroll.horiz.backward(steps=steps)
def scroll_to_horizontally(self, obj, *args,**attribute):
"""
return whether the object can be fling or not
"""
return obj.scroll.horiz.to(**attribute)
def scroll_forward_vertically(self, obj, steps=10):
"""
return whether the object can be fling or not
"""
return obj.scroll.vert.forward(steps=steps)
def scroll_backward_vertically(self, obj, steps=10):
"""
return whether the object can be fling or not
"""
return obj.scroll.vert.backward(steps=steps)
def scroll_to_vertically(self, obj, *args, **attribute):
"""
return whether the object can be fling or not
"""
msg = ''
for key, value in attribute.iteritems():
msg += ' %s=%s ' % (key, value)
print msg
# print 'args:' + args[0]
return obj.scroll.vert.to(**attribute)
#Screen Actions of the device
def screenshot(self, scale=None, quality=None):
"""
Take a screenshot of device and log in the report with timestamp
"""
output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
screenshot_path = '%s%s%s.png' % (output_dir, os.sep, st)
self.device.screenshot(screenshot_path, scale, quality)
logger.info('\n<a href="%s">%s</a><br><img src="%s">' % (screenshot_path, st, screenshot_path), html=True)
#Watcher
# def register_click_watcher(self, watcher_name, attributes, *condition_list):
# """
# The watcher click on the object which has the attributes when conditions match
# """
# print type(attributes)
# watcher = self.device.watcher(watcher_name)
# for condition in condition_list:
# watcher.when(**condition)
# watcher.click(**attributes)
# self.device.watchers.run()
# print 'register watcher:%s' % watcher_name
# return
def __unicode_to_dict(self, a_unicode):
a_dict = dict()
dict_item_count = a_unicode.count('=')
for count in range(dict_item_count):
equal_sign_position = a_unicode.find('=')
comma_position = a_unicode.find(',')
a_key = a_unicode[0:equal_sign_position]
if comma_position == -1:
示例2: AndroidDevice
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
#.........这里部分代码省略.........
if k and v:
shellcmd.append('-e')
shellcmd.append(k)
shellcmd.append(str(v))
shellcmd.append(pkgname)
result = self.d.server.adb.cmd(*shellcmd).communicate()
return result
def TODOinstallPackage(self, **kwargs):
pass
def TODOremovePackage(self, **kwargs):
pass
def press(self, keyname, waittime=1):
#hard, soft key: home,back,up,down,right,left,center,menu,power or ANDROID_KEYEVENT
self.d.press(keyname)
time.sleep(waittime)
return self
def click(self, x, y, waittime=1):
self.d.click(x, y)
time.sleep(waittime)
return self
def click_image(self, imagename, waittime=1, threshold=0.01):
'''
if the wanted image found on current screen click it.
if the wanted image not found raise exception and set test to be failure.
'''
expect_image_path = os.path.join(configer['right_dir_path'], imagename)
assert os.path.exists(expect_image_path), 'the local expected image %s not found!' % imagename
current_image_path = os.path.join(configer['report_dir_path'], imagename)
self.d.screenshot(current_image_path)
assert os.path.exists(current_image_path), 'fetch current screen shot image %s failed!' % imagename
pos = getMatchedCenterOffset(expect_image_path, current_image_path, threshold)
assert pos, 'Fail Reason: The wanted image \'%s\' not found on screen!' % imagename
self.d.click(pos[0], pos[1])
time.sleep(waittime)
return self
def swipe(self, sx, sy, ex, ey, steps=100, waittime=1):
self.d.swipe(sx, sy, ex, ey, steps)
time.sleep(waittime)
return self
def drag(self, sx, sy, ex, ey, steps=100, waittime=1):
self.d.drag(sx, sy, ex, ey, steps)
time.sleep(waittime)
return self
#inspect
def exists(self, **kwargs):
'''
if the expected component exists on current screen layout return true else return false.
'''
return self.d.exists(**kwargs)
#device snapshot
def screenshot(self, filename, waittime=1):
path = os.path.join(configer['report_dir_path'], filename)
self.d.screenshot(path)
return self
def expect(self, imagename, interval=2, timeout=4, threshold=0.01, msg=''):
'''
示例3: AndroidDevice
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
class AndroidDevice(object):
'''
wrapper for android uiautomator-server binding(pip install uiautomator).
provide android device event inject, ui object inspect and image comparison.
'''
def __init__(self, seral=None):
'''
create device instance.
'''
self.serial = os.environ[ANDROID_SERIAL] if os.environ.has_key(ANDROID_SERIAL) else None
self.working_dir_path = WORKING_DIR_PATH
self.report_dir_path = REPORT_DIR_PATH
self.right_dir_path = WORKING_DIR_PATH
self._internal_storage_dir = DEFAULT_DEVICE_INTERNAL_STORAGE
self.d = Device(self.serial)
#try:
# if int(self.d.info['sdkInt']) <= 17:
# self.d.screenshot = self.screenshot_common
#except:
# pass
def set_internal_storage_dir(self, path):
self._internal_storage_dir = path
def __getattr__(self, attr):
'''
forward method/attrbuite to uiautomator device if method support by uiautomator.
'''
if hasattr(self.d, attr):
if attr == 'screenshot':
return self.screenshot_common
m = getattr(self.d, attr)
if inspect.ismethod(m):
def wrapper(*args, **kwargs):
return m(*args, **kwargs)
return wrapper
else:
return m
raise AttributeError(attr)
def __call__(self, *args, **kwargs):
'''
selector support:
d(text="Settings").click()
'''
return self.d(*args, **kwargs)
@property
def orientation(self):
return self.d.orientation
@orientation.setter
def orientation(self, v):
self.d.orientation = v
def serial(self):
'''
device serial number from $ANDROID_SERIAL
'''
return self.serial
def sleep(self, sec):
time.sleep(sec)
#device event inject
def start_activity(self, **intent_params):
'''
Starts an Activity on the device by sending an Intent which constructed from the specified parameters.
The params of Intent supported from adb docs:
<INTENT> specifications include these flags:
[-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
[-c <CATEGORY> [-c <CATEGORY>] ...]
[-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
[--esn <EXTRA_KEY> ...]
[--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
[-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
[-n <COMPONENT>] [-f <FLAGS>]
[<URI>]
@type intent_params: dictionary
@param intent_params: the properties of an Intent.
property support: component/action/data/mimetype/categories/extras/flags/uri
@rtype: AndroidDevice
@return: a instance of AndroidDevice.
'''
#d.server.adb.cmd('shell','am', 'start', '-a', 'android.intent.action.DIAL','tel:13581739891').communicate()
#sys.stderr.write(str(intent_params))
keys = intent_params.keys()
shellcmd = ['shell', 'am', 'start']
if 'component' in keys:
shellcmd.append('-n')
shellcmd.append(intent_params['component'])
if 'action' in keys:
shellcmd.append('-a')
shellcmd.append(intent_params['action'])
if 'data' in keys:
shellcmd.append('-d')
#.........这里部分代码省略.........
示例4: Mobile
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
#.........这里部分代码省略.........
See for more details: https://github.com/xiaocong/uiautomator#screen-actions-of-the-device
"""
return self.device.orientation
def set_screen_orientation(self, orientation):
"""
Set the screen orientation.
Input *orientation* : natural or n, left or l, right or r, upsidedown (support android version above 4.3)
The keyword will unfreeze the screen rotation first.
See for more details: https://github.com/xiaocong/uiautomator#screen-actions-of-the-device
Example:
| Set Screen Orientation | n | # Set orientation to natural |
| Set Screen Orientation | natural | # Do the same thing |
"""
self.device.orientation = orientation
def freeze_screen_rotation(self):
"""
Freeze the screen auto rotation
"""
self.device.freeze_rotation()
def unfreeze_screen_rotation(self):
"""
Un-Freeze the screen auto rotation
"""
self.device.freeze_rotation(False)
def screenshot(self, scale=None, quality=None):
"""
Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality
default scale=1.0 quality=100
"""
output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
screenshot_path = '%s%s%s.png' % (output_dir, os.sep, st)
self.device.screenshot(screenshot_path, scale, quality)
logger.info('\n<a href="%s">%s</a><br><img src="%s">' % (screenshot_path, st, screenshot_path), html=True)
#Watcher
# def register_click_watcher(self, watcher_name, selectors, *condition_list):
# """
# The watcher click on the object which has the selectors when conditions match
# """
# print type(selectors)
# watcher = self.device.watcher(watcher_name)
# for condition in condition_list:
# watcher.when(**condition)
# watcher.click(**selectors)
# self.device.watchers.run()
# print 'register watcher:%s' % watcher_name
# return
def __unicode_to_dict(self, a_unicode):
a_dict = dict()
dict_item_count = a_unicode.count('=')
for count in range(dict_item_count):
equal_sign_position = a_unicode.find('=')
comma_position = a_unicode.find(',')
a_key = a_unicode[0:equal_sign_position]
示例5: UiTestLib
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
#.........这里部分代码省略.........
def freeze_rotation(self, rotation=True):
"""
Freeze rotation,
*rotation*, True is default,
"""
return self.d.freeze_rotation(rotation)
def set_rotation(self, rotation):
"""
# retrieve orientation,
# it should be "natural" or "left" or "right" or "upsidedown"
Example:
| Action | Argument |
| Set Rotation | nature |
| Set Rotation | left |
| Set Rotation | right |
| Set Rotation | upsidedown |
"""
orientation = self.d.orientation
if rotation == "nature":
self.d.orientation = "n" # or "natural"
elif rotation == "left":
self.d.orientation = "l" # or "left"
elif rotation == "right":
self.d.orientation = "r" # or "right"
elif rotation == "upsidedown":
self.d.orientation = "upsidedown" # or "upsidedown"
else:
self.d.rotation = "n"
def take_screenshot(self, scale=None, quality=None):
"""
Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality
default scale=1.0 quality=100
Example:
| Action | Argument | Argument |
| Take Screenshot | 0.5 | 80 |
"""
output_dir = BuiltIn().get_variable_value("${OUTPUTDIR}")
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%Y%m%d%H%M%S")
screenshot_path = "%s%s%s.png" % (output_dir, os.sep, st)
screenshot_name = "%s%s.png" % (os.sep, st)
self.d.screenshot(screenshot_path, scale, quality)
logger.info('\n<a href="%s">%s</a><br><img src="%s">' % (screenshot_path, st, screenshot_name), html=True)
def open_notification(self):
"""
Open notification of the phone
"""
self.d.open.notification()
def wait_window_update(self):
"""
wait for window update
"""
return self.d.wait.update()
def wait_window_idle(self):
"""
wait for window idle
"""
示例6: hold_call
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
def hold_call(callee):
d=Device(callee.id,adb_server_host='127.0.0.1',adb_server_port=5037)
print "finding the button"
d(resourceId='com.asus.asusincallui:id/holdButton').click()
d.screenshot('incall.png')
print "pressed the button"
示例7: AdbDevice
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
#.........这里部分代码省略.........
else:
self._setScreenOrient(index)
def volumeUp(self):
self.cmd.inputKeyevnt('VOLUME_UP')
def volumeDown(self):
self.cmd.inputKeyevnt('VOLUME_DOWN')
# def _setAutoRotate(self, status):
# if status:
# self.cmd.shell(['content', 'insert', '--uri', 'content://settings/system', '--bind', 'name:s:accelerometer_rotation',
# '--bind', 'value:i:1'])
# time.sleep(1)
# self.cmd.shell(['content', 'insert', '--uri', 'content://settings/system', '--bind', 'name:s:accelerometer_rotation',
# '--bind', 'value:i:1'])
#
# else:
# self.cmd.shell(['content', 'insert', '--uri', 'content://settings/system', '--bind', 'name:s:accelerometer_rotation',
# '--bind', 'value:i:0'])
# time.sleep(1)
# self.cmd.shell(['content', 'insert', '--uri', 'content://settings/system', '--bind', 'name:s:accelerometer_rotation',
# '--bind', 'value:i:0'])
def _setScreenOrient(self, orient):
self.cmd.shell(['content', 'insert', '--uri', 'content://settings/system', '--bind', 'name:s:user_rotation',
'--bind', 'value:i:' + str(orient)])
def resetPackage(self, package):
self.cmd.shell(['pm', 'clear', package])
def takeSnapshot(self, path):
return self.d.screenshot(path)
def getCurrDisplay(self):
output = self.cmd.dumpsys(['display'])
match = re.search('mCurrentOrientation=(?P<orientation>[\d])[\w\d\s\(\),-=]+'
+ 'mCurrentDisplayRect=Rect\(0, 0 - (?P<width>[\d]+),\s+(?P<height>[\d]+)', output)
width = int(match.group('width'))
height = int(match.group('height'))
orientation = int(match.group('orientation'))
mode = 'landscape' if width > height else 'portrait'
return {'width': width, 'height': height, 'orientation': orientation, 'mode': mode}
def getRealDisplay(self):
output = self.cmd.dumpsys(['display'])
match = re.search('real\s(?P<width>[\d]+)\sx\s(?P<height>[\d]+)', output)
return {'width': int(match.group('width')), 'height': int(match.group('height'))}
def getProp(self, propType=None):
if propType:
return self.cmd.shell(['getprop', propType], output=True).strip('\n')
else:
return self.cmd.shell(['getprop'], output=True).strip('\n')
def uninstall(self, package):
self.cmd.uninstall(package)
def install(self, name):
self.cmd.install(name)
def close(self):
pass
def checkConnected(self):
示例8: __init__
# 需要导入模块: from uiautomator import Device [as 别名]
# 或者: from uiautomator.Device import screenshot [as 别名]
#.........这里部分代码省略.........
return output.split(':')[1].strip()
def install_build(self):
os.system("adb -s {} root".format(self.monitor_serial))
os.system("adb -s {} wait-for-device remount".format(self.monitor_serial))
time.sleep(6)
commandToExecute = ("adb -s {} push {} /system/".format(self.monitor_serial, self.build_location))
os.system(commandToExecute)
time.sleep(1)
self.reboot_mon()
def reboot_mon(self):
checkBootComp = 'adb {} shell getprop sys.boot_completed'.format(self.specifying_monitor)
output = subprocess.check_output([c for c in checkBootComp.split()])
print('start rebbot monitor')
os.system('adb {} reboot'.format(self.specifying_monitor))
self.is_boot_completed(output)
print('reboot monitor completed')
def is_boot_completed(self, bootCompCmd):
output = '-1'
while output != bootCompCmd:
time.sleep(1)
try:
screenUp = 'adb {} shell getprop sys.boot_completed'.format(self.specifying_monitor)
output = subprocess.check_output([s for s in screenUp.split()])
except Exception:
print('waiting for monitor')
print('Screen up and fully loaded')
return True
def do_factory_reset(self):
checkBootComp = 'adb {} shell getprop sys.boot_completed'.format(self.specifying_monitor)
output = subprocess.check_output([c for c in checkBootComp.split()])
print('Start doing reboot to the monitor')
self.device(resourceId="com.screenovate.dell.monitorserver:id/settings").click()
self.device(resourceId="com.screenovate.dell.monitorserver:id/reset").click()
self.device(resourceId="com.screenovate.dell.monitorserver:id/reset_ok").click()
print('Start doing factory rest...')
os.system("adb {} logcat".format(self.specifying_monitor))
self.is_boot_completed(output)
def set_wifi_channel(self, channel):
print('Setting wifi channel to {} '.format(channel))
self.device(resourceId="com.screenovate.dell.monitorserver:id/settings").click()
self.device(resourceId="com.screenovate.dell.monitorserver:id/set_wifi_channel").click()
auto_is_checked = self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_auto_checkbox").info['checked']
channel_24_is_checked = self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_auto24_checkbox").info['checked']
channel_5_is_checked = self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_auto5_checkbox").info['checked']
if auto_is_checked or channel_5_is_checked or channel_24_is_checked:
self.device(resourceId="com.screenovate.dell.monitorserver:id/show_advanced").click()
self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_custom_checkbox").click()
self.device(text=channel, className="android.widget.TextView").click()
self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_ok").click()
def get_build_version(self):
build_name = self.build_location
return build_name[build_name.find('K-') + 2:build_name.find("/sys")]
def check_build_version(self):
print('checking version of the build')
build_version = 'adb {} shell dumpsys package com.screenovate.dell.monitorserver'.format(
self.specifying_monitor)
output = subprocess.check_output([b for b in build_version.split()])
return ("versionName={}".format(self.build_version) in output)
def get_monitor_name_by_adb(self):
dumpsys = "adb shell dumpsys | {} wifiP2pDevice=Device".format(self.find_command)
output = subprocess.check_output([c for c in dumpsys.split()])
start_index = output.rfind('Device: ', 0)
start_index = start_index + 8
end_index = output.rfind("\n", 0)
name = output[start_index: end_index].strip()
return name
def verify_nothing_connected(self):
print('verifying nothing connected')
if self.device.exists(resourceId="com.screenovate.dell.monitorserver:id/video_view"):
print('some device connected to monitor , stsrt rebooting monitor')
self.reboot_mon()
print('no device currently connected to monitor')
def get_monitor_name_by_ui(self):
self.verify_nothing_connected()
print("get name from " + self.monitor_serial)
self.monitor_name = self.device(resourceId="com.screenovate.dell.monitorserver:id/ssid").info[
"text"]
return self.monitor_name
def screen_on(self):
print("turning monitor screen on")
os.system("adb {} shell input keyevent 82".format(self.specifying_monitor))
def take_screenshot_test(self):
self.device.screenshot("pictures-test/monitor.png")