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

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.

主站蜘蛛池模板: 大竹县| 安顺市| 洛川县| 盐津县| 洪泽县| 盐亭县| 丰原市| 武冈市| 南木林县| 澄江县| 美姑县| 银川市| 彩票| 阿鲁科尔沁旗| 油尖旺区| 安西县| 揭西县| 盐津县| 锡林郭勒盟| 廉江市| 太康县| 克东县| 沙雅县| 赞皇县| 顺平县| 肥东县| 玉龙| 祁阳县| 庆元县| 东乡县| 清镇市| 泽州县| 仙游县| 株洲市| 乐亭县| 时尚| 外汇| 汉源县| 连州市| 普兰县| 香港 |