These are the lines you should add to every monkeyrunner script. Here you are a brief explanation of the snippet.

The shebang line to invoke monkeyrunner interpreter if you are using Linux or Mac OS X. Unfortunately this is not available on Windows. Eclipse does not use this line but is needed if you want to simplify the way you are running the scripts from the command line.

Some standard imports

PyDev uses PYTHONPATH while monkeyrunner ignores it. This snippet adds the components present in PYTHONPATH to sys.path and makes them visible to monkeyrunner.

Following, we need to locate AndroidViewClient which you should have added to the environment. This can be also added in Eclipse in Run Configurations -> Environment.ANDROID_VIEW_CLIENT_HOME should point to your AndroidViewClient installation to the parent folder of src. That is, if you have downloaded AndroidViewClient in /opt/AndroidViewClient and kept the same structure as the distribution, you should set ANDROID_VIEW_CLIENT_HOME=/opt/AndroidViewClient/AndroidViewClient

The imports, which will now succeed because sys.path contains the right components

Gets the device's serial number from the command line or default to emulator-5554.

Connect to the device

Check if the connection was successful. Because MonkeyRunner.waitForConnection() returns a MonkeyDevice even when the connection fails we need to go to this extra step to verify it.