OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2012 The Native Client Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import os |
| 6 import subprocess |
| 7 import tempfile |
| 8 |
| 9 |
| 10 def DataToReadableHex(data): |
| 11 """Convert string of bytes to string of hexes ('\xde\xad' -> 'de ad'). |
| 12 |
| 13 Args: |
| 14 data: String (used to represent sequence of bytes). |
| 15 |
| 16 Returns: |
| 17 String of space-separated hex codes. |
| 18 """ |
| 19 |
| 20 return ' '.join('%02x' % ord(c) for c in data) |
| 21 |
| 22 |
| 23 def ReadableHexToData(s): |
| 24 """Convert string of hexes to string of bytes ('be ef' -> '\xbe\xef'). |
| 25 |
| 26 Args: |
| 27 s: String of space-separated two-character hex codes. |
| 28 |
| 29 Returns: |
| 30 String representing sequence of bytes. |
| 31 """ |
| 32 |
| 33 bytes = s.split() |
| 34 assert all(len(byte) == 2 for byte in bytes) |
| 35 return ''.join(chr(int(byte, 16)) for byte in bytes) |
| 36 |
| 37 |
| 38 def CheckOutput(args, **kwargs): |
| 39 # reimplementation of subprocess.check_output from py 2.7 |
| 40 assert 'stdout' not in kwargs |
| 41 |
| 42 process = subprocess.Popen(args, stdout=subprocess.PIPE, **kwargs) |
| 43 output, _ = process.communicate() |
| 44 |
| 45 if process.returncode != 0: |
| 46 raise subprocess.CalledProcessError(process.returncode, cmd=args[0]) |
| 47 |
| 48 return output |
| 49 |
| 50 |
| 51 # Custom context manager that allows temporary file to be reopened |
| 52 # and deletes it on exit. |
| 53 # NamedTemporareFile with delete=True won't do the job because |
| 54 # it can't be reopened on Windows. |
| 55 class TempFile(object): |
| 56 def __init__(self, mode='w+b'): |
| 57 self.file = tempfile.NamedTemporaryFile(mode=mode, delete=False) |
| 58 |
| 59 def __enter__(self): |
| 60 return self.file |
| 61 |
| 62 def __exit__(self, exc_type, exc_value, traceback): |
| 63 self.file.close() |
| 64 |
| 65 # The check is needed because gnu style compilers (AS in particular) |
| 66 # have habit to delete output file when there are compilation errors. |
| 67 if os.path.exists(self.file.name): |
| 68 os.remove(self.file.name) |
OLD | NEW |