Python スクリプトやシステムコマンド(ls, git, npm 等)をアプリから呼び出す方法を解説します。
Tauri v2 では @tauri-apps/plugin-shell を使用します。
前提条件
プラグインのインストールが必要です。
npm run tauri add shell
Permissions (権限) の設定
src-tauri/capabilities/default.json に以下の権限を追加します。
{
"permissions": [
...,
"shell:allow-execute",
"shell:allow-open",
{
"identifier": "shell:allow-execute",
"allow": [
{
"name": "ls",
"cmd": "ls",
"args": true
},
{
"name": "python",
"cmd": "python3",
"args": true
}
]
}
]
}
1. フロントエンドから作成する (TypeScript)
Command.create(name) でインスタンスを作成し、execute() で実行します。
単純なコマンド実行
import { Command } from '@tauri-apps/plugin-shell';
async function runList() {
try {
const cmd = Command.create('ls', ['-la']);
const output = await cmd.execute();
if (output.code === 0) {
console.log('Success:', output.stdout);
} else {
console.warn('Error:', output.stderr);
}
} catch (error) {
console.error('Execution Failed:', error);
}
}
runList();
2. バックエンドから作成する (Rust)
バックエンド(Rust)から外部コマンドを実行する場合は、標準ライブラリの std::process::Command を使用します。
この場合、capabilities のスコープ設定に関わらず実行可能ですが、任意のコマンドを実行できるためセキュリティには十分注意してください。
use std::process::Command;
#[tauri::command]
fn run_ls() -> Result<String, String> {
let output = Command::new("ls")
.arg("-la")
.output()
.map_err(|e| e.to_string())?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
Ok(stdout.to_string())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(stderr.to_string())
}
}