How to print to file in AMPL? `option log_file` doesn't work

3k views Asked by At

I want to use some printf to print to a file.

I can use

for{i in set1}  printf '%10.5f\n',var1[i] >> ('a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo));
for{i in set2}  printf '%10.5f\n',var2[i] >> ('a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo));
for{i in set3}  printf '%10.5f\n',var3[i] >> ('a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo));

But I don't want to repeat the file each time.

It seems option log_file should do the trick, but doesn't work for me: the file is created but empty, and the output is printed in the console.

2

There are 2 answers

5
Oriol On BEST ANSWER

I have discovered that I must change option log_file after printing, because it seems that AMPL doesn't close the file, even if I use close.

Then, the following works:

print "Hello, ";              # Printed to the console
option log_file "test.txt";
print "World";                # Printed to the console and file
option log_file ""; 
close;
1
vitaut On

To avoid repeating the file name, store it in a parameter:

param out symbolic =
  'a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo);
for{i in set1} printf '%10.5f\n',var1[i] >> (out);
for{i in set2} printf '%10.5f\n',var2[i] >> (out);
for{i in set3} printf '%10.5f\n',var3[i] >> (out);

Note that the parentheses around out are important, because they allow passing an expression (a parameter reference in this case) rather than verbatim text as a file name.