Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Environment variable using Process.start

Tags:

dart

Is it possible to set an environment variable using Process.start()? I've tried to adapt the Process example from http://www.dartlang.org/articles/io/ but I am receiving errors.

Process.start("export my_key='abc123'", []).then((process) {
  var stdoutStream = new StringInputStream(process.stdout);
  stdoutStream.onLine = () => print(stdoutStream.readLine());
  process.stderr.onData = process.stderr.read;
  process.onExit = (exitCode) {
    print('exit code: $exitCode');
};

Errors:

Unhandled exception:
FutureUnhandledException: exception while executing Future
  ProcessException: No such file or directory
    Command: export my_key='abc123' 
original stack trace:
  null
#0      _FutureImpl._complete (bootstrap:844:11)
#1      _FutureImpl._complete (bootstrap:848:5)
#2      _FutureImpl._setException (bootstrap:873:14)
#3      _CompleterImpl.completeException (bootstrap:948:30)
#4      _ProcessImpl._start.<anonymous closure> (dart:io-patch:198:37)
#5      _Timer._createTimerHandler._handleTimeout (dart:io:6918:28)
#6      _Timer._createTimerHandler._handleTimeout (dart:io:6926:7)
#7      _Timer._createTimerHandler.<anonymous closure> (dart:io:6934:23)
#8      _ReceivePortImpl._handleMessage (dart:isolate-patch:37:92)
like image 398
basheps Avatar asked Feb 19 '23 03:02

basheps


1 Answers

Unfortunately no you cannot. First this is because export is actually a shell command of bash (or several other shells) and not an actual application on the system. Dart does not execute processes within a shell.

An option is to use bash -c 'export my_key=123' as the parameter passed to Process.start, however this is also of very limited use as exported variables only exist for the duration of the bash session. That is, once your spawned process terminates, your variable no longer exists.

If you want to see this in action try something like this from your command prompt:

bash -c 'export TEST="true";echo $TEST'

This will create a new bash session, export the variable, then display the variable. Once you have your prompt try then running:

echo $TEST

by itself. You should see a blank line (or a different value if that already exists on your system).

That said, if you want to set an environment variable before running a different process, please use the ProcessOptions class to set the environment variable then pass that to your Process.start as such:

import 'dart:io';

void main() {
  var po = new ProcessOptions();
  var ev = {'TEST': 'True'};
  po.environment = ev;
  Process.start('bash', ['-c','export'], po).then((process) {
    var stdoutStream = new StringInputStream(process.stdout);
    stdoutStream.onLine = () => print(stdoutStream.readLine());
    process.stderr.onData = process.stderr.read;
  });
}
like image 54
Matt B Avatar answered Mar 23 '23 06:03

Matt B