Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive

MathGroup Archive 2013

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Running an external program inside a Do loop

  • To: mathgroup at
  • Subject: [mg130504] Re: Running an external program inside a Do loop
  • From: Peter Pein <petsie at>
  • Date: Wed, 17 Apr 2013 02:29:41 -0400 (EDT)
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:
  • References: <kk88r9$c1b$>

Am 12.04.2013 08:16, schrieb Luiz Melo:
> Hi
> I have to run an external program inside a Do loop, as in the example
> below. The .exe program takes the parameter i as input from the
> Input.dat file, and  generates a two-column numerical .dat file as
> output. Next, the Output.dat file has to be imported and manipulated.
> Since the external program takes some time to run and the Do loop runs
> much faster, the external program is terminating abnormaly. I would
> like to know how to tell Mathematica to wait until the external
> program finishes its evaluation before to execute the Import command.
> Thank you.
> Luiz Melo.
> Do [
>  Export["Input.dat", i];
>  Run["SomeMath.exe"];
>  t = Import["Output.dat"];
>  tpos[i] = Select[t, #[[1]] > 0 &];
>  tneg[i] = Select[t, #[[1]] < 0 &], {i, 100}];

Hi Luiz,

 I can not reproduce this behaviour. I wrote a simple program
'SomeMath.c" whichs sleeps three seconds before it writes the output to

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
  int number;
  FILE *ifile = fopen("input.dat", "r");
  FILE *ofile = fopen("output.dat", "w");

  fscanf(ifile, "%d", &number);
  fprintf(ofile, "%d\n", number*number);

and with

  Export["input.dat", i];
  timerr = AbsoluteTiming@Run["SomeMath.exe"];
  {t} = Import["output.dat"][[1]];
  Print[Grid[{{"Time", "err-code", "input", "output"},
     Join[timerr, {i, t}]}]];
  , {i, 2}
DeleteFile[# <> "put.dat" & /@ {"in", "out"}];

I get:

  Time      err-code  input   output
3.095177	0	1	1

  Time      err-code  input   output
3.092177	0	2	4

you could try ReadList as in:

    t=First@ReadList["!SomeMath.exe & type output.dat",
  Print[i,", ",t];,

which prints

1, {1}
2, {4}

and has got at least the advantage that these annoying console windows
do not appear. This calls SomeMath.exe and types the output to stdout as
_one_ command. Maybe this helps in your case.

Good luck,

  • Prev by Date: Re: Plot with axes exchanged
  • Next by Date: Re: Plot with axes exchanged
  • Previous by thread: Running an external program inside a Do loop
  • Next by thread: Re: Running an external program inside a Do loop