# 執行 Shell 命令

此功能可讓您在裝置上執行 Shell 命令或完整的 Shell 腳本。所有命令都將以 root 身份執行。同時，為了相容長期執行的腳本，本功能也支援在背景執行不退出的腳本。

## 前景命令執行

您可以如下方所示快速執行一個命令或腳本。此操作會阻塞當前程序，因此您的腳本或命令的執行時間不應太長，適用於執行時間較短（0-10 秒內）的腳本。

```python
cmd = d.execute_script("whoami")
```

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

輸出會返回狀態碼，以及標準輸出和標準錯誤。

```python
print (cmd.stdout)
print (cmd.stderr)
print (cmd.exitstatus)
```

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

## 背景命令執行

背景命令執行適用於執行時間較長的腳本。考量到使用者可能會寫出無限迴圈或腳本無限輸出等導致記憶體佔滿的情況，此方法無法獲知背景腳本的執行結果。如果您需要獲取腳本的輸出資訊，請自行在腳本中將輸出寫入檔案。

下方的呼叫將執行一個長時間執行的腳本 `sleep`，並返回一個 `sid` 字串，此字串為該背景腳本的 ID。

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

如果腳本出現非預期的狀況，您也可以透過下方的呼叫，強制結束正在背景執行的腳本。

```
d.kill_background_script(sid)
```

您可以透過下方的呼叫，藉由 `sid` 檢查背景腳本是否已執行完畢。

```python
d.is_background_script_finished(sid)
```

```python
>>> 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
```