Category Archives: Python Script

Script for doing screen captures

Created a screen for doing screen captures, so I can call it while doing other test.  This script uses the time to create an unique file name, so I don’t have to worry about overwriting the same file while running my test.  This script is run by monkeyrunner so I used the full path when calling monkeyrunner and my script (this is a bit bias towards OS X syntax since I am testing on a Mac at the moment)

/Users/me/Android/sdk/tools/monkeyrunner -v ALL  /Users/me/Android/capture_screen.py

-v ALL is for verbose logging

#!/usr/bin/env python
# coding: utf-8

# Screen shot of android

# Needed modules
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

import time

# Wait for connection
device = MonkeyRunner.waitForConnection()

# Use the time in seconds to help create an unique file name for the image that is captured

filelocation = "/Users/jmiller/Android/Screen_Shots/"

fileNamePrefix = "scrnCap"

thefile = filelocation + fileNamePrefix + str(int(time.time())) + ".png"

# Snap shot of the screen
result = device.takeSnapshot()

# Write out the results
result.writeToFile(thefile,"png")

Turning the output from getevent into something something that can be used

My end goal was to to be able to “doodle” on the android screen, with a script.  I can’t do the math to generate the image I want, so I ran the adb shell command “getevent” then using the mouse, I drew on the screen.

However the output isn’t immediately usable, first there was the minor problem of it containing a colon which would throw an error when I tried to run it.  The second and bigger issue, is that the getevent command captures everything in hexadecimal, but the command sendevent, requires everything to be in decimal.  Since monkeyrunner is basically python (the docs say jython, but I haven’t used anything that advance yet), I wrote a python script, that takes an input file containing a bunch of lines that look like this:

/dev/input/event0: 0003 0000 00000073
/dev/input/event0: 0003 0001 000000a8
/dev/input/event0: 0001 014a 00000001
/dev/input/event0: 0000 0000 00000000
/dev/input/event0: 0003 0001 000000a4

And created a new output file with adb shell commands that look like this:

adb shell sendevent /dev/input/event0 3 0 115
adb shell sendevent /dev/input/event0 3 1 168
adb shell sendevent /dev/input/event0 1 330 1
adb shell sendevent /dev/input/event0 0 0 0
adb shell sendevent /dev/input/event0 3 1 164

Which can be run and do the drawing for me on the screen.  This worked, but running a bunch of adb shell commands is really, really slow.  So I tweaked my python script, and instead have to create something like:

#!/bin/sh
echo Running – signature function
sendevent /dev/input/event0 3 0 115
sendevent /dev/input/event0 3 1 168
sendevent /dev/input/event0 1 330 1
sendevent /dev/input/event0 0 0 0
sendevent /dev/input/event0 3 1 164
sendevent /dev/input/event0 0 0 0
……..

This is copied to the device, and run as a local script and runs at an ok speed (not really fast, but much faster than adb shell commands) – the python script prints out instructions with the exact command to run, to copy the file to the device and what to execute it run it.  I will post the python separately, I am new to this code so the code isn’t prefect, but it works and meets my needs.ew

The steps are

  1. Run the app (I did it in the emulator)
  2. Run the command adb shell getevent, om whatever screen you want to doodle/draw on – the output is dumped to the screen
  3. Capture that output when you are done (copy it, usually by right clicking and choosing mark, highlight the area and then hit enter)
    1. Paste the info into notepad, and save it to any file name you want (i.e. captured.dat)
  4. Run the script
    1. hex_to_dec.py captured.dat
      1. catpured.bat is the input data for the script
  5. The script runs pretty fast and kicks out a file captured.scr (the code can be updated to name the file anything)
    1. The script prints out instructions for coping the script to the device and for running the script, that looks something like this

C:\>hex_to_dec.py raw_captured_sig.dat
Processing complete
File created: raw_captured_sig.scr

Copy file to the device
adb push raw_captured_sig.scr /sdcard/raw_captured_sig.scr

Run the script
adb shell sh /sdcard/raw_captured_sig.scr

Python script to convert hexadecimal to decimal for sendevent (hex_to_dec.py)

#!/usr/bin/env python
# coding: utf-8

# From hex_to_dec.py (which I created a while ago)

# Tweaking for Mac
#
# Fixed indenting that wordpress was breaking
#
# You need python installed – more info here:
# Python – http://www.python.org/download/
# The Purpose of this script
#
# Script name: hex_to_dec.py
#
# To turn the getevent output from this:
# /dev/input/event0: 0003 0001 00000092
# to this (something can be run)
# sendevent /dev/input/event0 3 1 92
# Outfile of what to do
# List input file on command line when running
# Open file
# prefix “adb shell sendevent” command to line
# remove colon from input
# convert 3 hexidecimal values to decimal values
# Assemble new complete line
# write out line to new file,
# named the original filename +suffix “bat” – windows batch file ready to run
#

# Importing Stuff
import sys
import fileinput
###################################################################################################
#
# Variables
#

# Command prefix
prefix = "sendevent "

inputline = ""
complete = ""
part1len = 0
part1 = ""
part2 = ""

num1 = 0
num2 = 0
num3 = 0

# File stuff
rawfile = ""
outfile = ""
filename = ""
###################################################################################################
#
# File operations
#

# Grabs the file name from the command line when you run the python script
rawfile = sys.argv[-1]

# Open the input file
# r – Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
# w – Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
#
fo = open(rawfile, "r")

# Create output file, taking everything in front of the . (kind of windows centric)
filename = rawfile.find(".");
outfile = rawfile[:filename] + ".scr"

# Output file
fw = open(outfile, "w")

# Stuff at the top of the script (first commands to run)
# Puts into bash
fw.write("#!/bin/sh" + "\n")

# User Message
fw.write("echo Running – drawing function " + "\n")

###################################################################################################
#
# Process input string, creating new formatted command
#

for inputline in fo.read().split("\n"):
        # Used for testing/debug
	#print inputline

	# Otherwise let"s process the line
	# Find the location of the colon
	part1len = inputline.find(":");

	# -1 means end of file so quit processing
	if part1len > -1:
		# Only take the first part of the string up to the string
		part1 = inputline[:part1len];

		# Finding the hexidecimal values
		# Splits the string based on spaces, creating an array with 4 strings,
		part2 = inputline.split(" ");

		# we want strings 1,2,3 (since arrays start at 0 (zero))
		# we need to specify the base explicitly (based 16, so hex gets converted to decimal)
		num1 = int(part2[1], 16)
		num2 = int(part2[2], 16)
		num3 = int(part2[3], 16)

		# Put is all together
		complete = prefix + part1 + " " + str(num1) + " " + str(num2) + " " + str(num3)

		# Write out to the file, with a new line feed
		fw.write(complete + "\n")

# For testing
#print complete

# Info for the user
print "Processing complete"
print "File created: ", outfile
print
print "Copy file to the device"
print "adb push " + outfile + " /sdcard/" + outfile
print
print "Run the script"
print "adb shell sh /sdcard/" + outfile
###################################################################################################
#
# File clean up
#

# Close all files
fo.close()
fw.close()

Help.py (monkeyrunner)

Not my file  just a copy of what I found (file needs to be saved as help.py)

#!/usr/bin/env monkeyrunner
# Copyright 2010, The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the “License”);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an “AS IS” BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from com.android.monkeyrunner import MonkeyRunner as mr

import os
import sys

supported_formats = [‘html’, ‘text’, ‘sdk-docs’]

if len(sys.argv) != 3:
print ‘help.py: format output’
sys.exit(1)

(format, saveto_path) = sys.argv[1:]

if not format.lower() in supported_formats:
print ‘format %s is not a supported format’ % format
sys.exit(2)

output = mr.help(format=format)
if not output:
print ‘Error generating help format’
sys.exit(3)

dirname = os.path.dirname(saveto_path)
try:
os.makedirs(dirname)
except:
print ‘oops’
pass # It already existed

fp = open(saveto_path, ‘w’)
fp.write(output)
fp.close()

sys.exit(0)