Command Execution¶
This feature allows you to execute shell commands or complete shell scripts on the device. All commands run under the user account used to run the service. To support long-running scripts, this feature also supports scripts that run in the background without exiting.
Foreground Command Execution¶
You can quickly execute a command or script as shown below. This operation blocks the current process, so your script or command should not run too long; it is suitable for scripts that take a short time (0–10 seconds).
cmd = d.execute_script("whoami")
>>> d.execute_script("notexist")
exitstatus: 127
stderr: "mksh: <stdin>[2]: notexist: inaccessible or not found\n"
After the command finishes, it returns the exit status, 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 suitable for long-running scripts. Given that users might write infinite loops or cause the script to produce infinite output that could fill up memory, the execution results of background scripts cannot be retrieved. If you need to obtain the script’s output, please redirect the output within the script.
The following example executes a long-running script sleep and returns an sid string as the ID of this background script.
script = "sleep 100; exit 0;"
sid = d.execute_background_script(script)
If the script encounters unexpected circumstances, you can forcibly terminate the running background script.
d.kill_background_script(sid)
Use sid to check whether the background script has finished running.
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