- 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
.
- 物聯(lián)網(wǎng)(IoT)基礎(chǔ):網(wǎng)絡(luò)技術(shù)+協(xié)議+用例
- 智能網(wǎng)聯(lián)汽車V2X與智能網(wǎng)聯(lián)設(shè)施I2X
- Building Django 2.0 Web Applications
- Spring Boot 2.0 Projects
- 局域網(wǎng)組建、管理與維護(hù)項(xiàng)目教程(Windows Server 2003)
- Drush User’s Guide
- 城市治理一網(wǎng)統(tǒng)管
- WordPress Web Application Development
- 6G新技術(shù) 新網(wǎng)絡(luò) 新通信
- Scala Design Patterns.
- 無線傳感器網(wǎng)絡(luò)定位技術(shù)
- Hands-On Docker for Microservices with Python
- Building RESTful Web Services with .NET Core
- 計(jì)算機(jī)通信網(wǎng)絡(luò)安全
- 算力網(wǎng)絡(luò):云網(wǎng)融合2.0時(shí)代的網(wǎng)絡(luò)架構(gòu)與關(guān)鍵技術(shù)