Fix permission issue when sandbox truncates output files

By wrapping the file object in a custom file-like truncator we avoid
touching the on-disk instance.

Using the io module gives us context managers for free.

Also improved escaping of command line arguments and made command files
be opened in text mode (i.e. accepting unicode) with default encoding
(i.e. UTF-8).
Add unit tests for Truncator.