def cleanup_commandline(commandline):
    """Clean up the commandline: remove trailing spaces and comments"""
    commandline = commandline.strip()
    instring = None
    for i in range(len(commandline)):
        if commandline[i] in ['"', "'"]:
            if instring == commandline[i]:
                instring = None
            elif instring is None:
                instring = commandline[i]
        if commandline[i] == '#' and instring is None:
            return commandline[:i].strip()
    if instring is not None:
        raise ValueError('Unterminated string in command line', commandline)
    return commandline.strip()
    return commandline.strip()
