Silentdoer

导航

dart集成shell脚本调用功能

pubspec.yaml里添加依赖:shell: any

import 'dart:io';

import 'package:shell/shell.dart';

void main(List<String> arguments) async {
  var shell = Shell();
  var password = Platform.environment['PASSWORD'];
  print('Password: $password');
  //password = "passwd";

  // Pipe results to files, easily.
  var echo = await shell.start('echo', arguments: ['hello world']);
  var kkk0 = await echo.stderr.readAsString();
  var kkk = await echo.stdout.readAsString();
  print("KKK-$kkk0");
  print("FFF-$kkk");

  // You can run a program, and expect a certain exit code.
  //
  // If a valid exit code is returned, stderr is drained, and
  // you don't have to manually.
  //
  // Otherwise, a StateError is thrown.
  var find = await shell.start('find', arguments: ['.']);
  await find.expectExitCode([0]); // Can also call find.expectZeroExit()

  // Dump outputs.
  print(await find.stdout.readAsString());

  // You can also run a process and immediately receive a string.
  var pwd = await shell.startAndReadAsString('pwd', arguments: []);
  print('cwd: $pwd');

  // Navigation allows you to `cd`.
  // 这个目录要存在
  shell.navigate('./lib');
  pwd = await shell.startAndReadAsString('pwd', arguments: []);
  print('cwd: $pwd');

  // We can make a separate shell, with the same settings.
  var forked = Shell.copy(shell)
    ..sudo = true
    ..password = password;

  // Say hi, as an admin!
  var superEcho = await forked.start('echo', arguments: ['hello, admin!']);
  await superEcho.expectExitCode([0, 1]);
  // 这里会要求sudo来执行,前面的password要先设置正确
  print("HHH-${await superEcho.stdout.readAsString()}");
}

 

posted on 2023-08-19 12:38  Silentdoer  阅读(90)  评论(0编辑  收藏  举报