Executing Shell Commands

This feature allows you to execute Shell commands or complete Shell scripts on the device. All commands will be executed with root privileges. At the same time, to accommodate long-running scripts, this feature also supports running scripts in the background without exiting.

Foreground Command Execution

You can use it like below to quickly execute a command or script. This operation will block the current process, so your script or command’s running time cannot be too long. It is used for executing scripts with short durations (within 0-10 seconds).

cmd = d.execute_script("whoami")
>>> d.execute_script("notexist")
exitstatus: 127
stderr: "mksh: <stdin>[2]: notexist: inaccessible or not found\n"

The output returns the status code, as well as standard output and standard error.

print (cmd.stdout)
print (cmd.stderr)
print (cmd.exitstatus)
>>> result = d.execute_script("id")
>>> print (result.stdout)
b'uid=0(root) gid=0(root)\n'
>>> print (result.stderr)
b''
>>> print (result.exitstatus)
0

Background Command Execution

Background command execution is used for scripts that run for a long time. Considering that users may write infinite loops or scripts with unlimited output, which can lead to memory being filled up, it is not possible to know the execution result of background scripts. If you want to get the output information of the script, please output to a file in the script yourself.

The following call will execute a long-running script sleep and return a string sid, which is the ID of this background script.

script = "sleep 100; exit 0;"
sid = d.execute_background_script(script)

If the script encounters unexpected situations, you can also forcibly end the script running in the background through the following call.

d.kill_background_script(sid)

You can check if the background script has finished running through sid with the following call.

d.is_background_script_finished(sid)
>>> script = "sleep 100; exit 0;"
>>> sid = d.execute_background_script(script)
>>> print (sid)
ba06da93-c3aa-4457-b90e-247e42a16207
>>> d.is_background_script_finished(sid)
False
>>> d.kill_background_script(sid)
True
>>> d.is_background_script_finished(sid)
True