manual_cpp 1.69 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess

def cpp_arg(arg):
    return arg.startswith("-I") or \
           arg.startswith("-D") or \
           arg.startswith("-U")


def check_call(args, **kwargs):
    if os.getenv("V") == "1":
        print(" ".join(args))
    return subprocess.check_call(args, **kwargs)

def check_call_redirect(args, filename=None, **kwargs):
    if os.getenv("V") == "1":
        print(" ".join(args), ">", filename)
    with open(filename, "wb") as fd:
22 23 24 25 26
        try:
            return subprocess.check_call(args, stdout=fd, **kwargs)
        except subprocess.CalledProcessError as e:
            os.remove(filename)
            raise SystemExit(e.returncode)
27 28 29 30 31 32 33 34 35 36

args = sys.argv[1:]
cpp_args = filter(cpp_arg, args)

files = filter(lambda q : q.endswith(".F90"), args)
args = filter(lambda q : not q.endswith(".F90"), args)
if len(files) > 1:
    raise Exception("Specify exactly one .F90 file")
elif len(files) == 0:
    # No .F90 file specified, execute program as-is
37 38 39 40 41
    try:
        os.execvp(args[0], args[0:])
    except OSError as e:
        print("Error executing '{0}': {1}".format(args[0], e.args[1]))
        raise SystemExit(1)
42 43
elif len(files) == 1:
    file, = files
44

45
tmp_filename = "manually_preprocessed_" + file.replace("/", "_")
46 47 48 49

try:
    output = args.index("-o")
    outputname = args[output + 1]
50
    tmp_filename += "-" + outputname.replace("/", "_") + ".F90"
51 52 53
except ValueError:
    pass

54 55
tmp_filename = tmp_filename[-250:]

56 57 58 59 60 61 62 63
# preprocess
check_call_redirect(["cpp","-P", "-traditional", "-Wall", "-Werror"] + cpp_args + [file], filename=tmp_filename)

# compile
check_call(args + [tmp_filename])

# cleanup
os.remove(tmp_filename)