官术网_书友最值得收藏!

  • Dart Cookbook
  • Ivo Balbaert
  • 208字
  • 2021-08-05 17:42:46

Making a system call

A fairly common use case is that you need to call another program from your Dart app, or an operating system command. For this, the abstract class Process in the dart:io package is created.

How to do it...

Use the run method to begin an external program as shown in the following code snippet, where we start Notepad on a Windows system, which shows the question to open a new file tst.txt (refer to make_system_call\bin\ make_system_call.dart):

import 'dart:io';

main() {
  // running an external program process without interaction:
 Process.run('notepad', ['tst.txt']).then((ProcessResult rs){
 print(rs.exitCode);
    print(rs.stdout);
    print(rs.stderr);
  });
}

If the process is an OS command, use the runInShell argument, as shown in the following code:

Process.run('dir',[], runInShell:true).then((ProcessResult 
rs)
{ … }

How it works...

The Run command returns a Future of type ProcessResult, which you can interrogate for its exit code or any messages. The exit code is OS-specific, but usually a negative value indicates an execution problem.

Use the start method if your Dart code has to interact with the process by writing to its stdin stream or listening to its stdout stream.

Note

Both methods work asynchronously; they don't block the main app. If your code has to wait for the process, use runSync.

主站蜘蛛池模板: 淮北市| 东港市| 泰兴市| 林州市| 镇江市| 丰都县| 宁海县| 丰宁| 商洛市| 秭归县| 望奎县| 崇阳县| 财经| 漳平市| 当雄县| 湟源县| 乐安县| 乡城县| 曲麻莱县| 齐河县| 上思县| 隆子县| 恭城| 喀喇沁旗| 闽侯县| 马边| 康乐县| 黑龙江省| 团风县| 云阳县| 牙克石市| 托克托县| 同心县| 舞阳县| 扶沟县| 阿拉善左旗| 郑州市| 昌邑市| 苍南县| 英吉沙县| 岐山县|