示例#1
0
def main():
    import getopt
    global verbose, recurse, dryrun, makebackup, nspaces
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "drnvNh",
            ["dryrun", "recurse", "nobackup", "verbose", "spaces", "help"])
    except getopt.error(msg):
        usage(msg)
        return
    for o, a in opts:
        if o in ('-d', '--dryrun'):
            dryrun += 1
        elif o in ('-r', '--recurse'):
            recurse += 1
        elif o in ('-n', '--nobackup'):
            makebackup = False
        elif o in ('-v', '--verbose'):
            verbose += 1
        elif o in ('-N', '--spaces'):
            nspaces = 4
        elif o in ('-h', '--help'):
            usage()
            return
    if not args:
        r = Reindenter(sys.stdin)
        r.run()
        r.write(sys.stdout)
        return
    for arg in args:
        check(arg)
示例#2
0
def main():
    import getopt
    global verbose, recurse, dryrun, makebackup, nspaces
    try:
        opts, args = getopt.getopt(sys.argv[1:], "drnvNh",
                        ["dryrun", "recurse", "nobackup", "verbose", "spaces", "help"])
    except getopt.error(msg):
        usage(msg)
        return
    for o, a in opts:
        if o in ('-d', '--dryrun'):
            dryrun += 1
        elif o in ('-r', '--recurse'):
            recurse += 1
        elif o in ('-n', '--nobackup'):
            makebackup = False
        elif o in ('-v', '--verbose'):
            verbose += 1
        elif o in ('-N', '--spaces'):
            nspaces = 4
        elif o in ('-h', '--help'):
            usage()
            return
    if not args:
        r = Reindenter(sys.stdin)
        r.run()
        r.write(sys.stdout)
        return
    for arg in args:
        check(arg)
def main():
    global mesPacked
    mesPacked = MesPacked()
    try:
        opts, args = getopt.getopt(sys.argv[1:], "")
        if len(args) > 2:
            raise getopt.error("Too many arguments.")
    except getopt.error as msg:
        usage(msg)
    for o, a in opts:
        pass
    if args:
        try:
            host = args[0]
            port = int(args[1])
        except ValueError as msg:
            usage(msg)
    else:
        host = loadSettings(1, mesPacked)
        port = loadSettings(2, mesPacked)

    module = sys.argv[0].split('/')[-1].split('.')[0]
    sys_info = "Starting {0} from Python:{1}.{2}\n".format(
        module, sys.version_info.major, sys.version_info.minor)
    print(sys_info)
    main_thread(host, port)
 def parseArgs(self, argv):
     global server
     import getopt
     try:
         options, args = getopt.getopt(argv[1:], 'hHvq',
                                       ['help','verbose','quiet'])
         for opt, value in options:
             if opt in ('-h','-H','--help'):
                 self.usageExit()
             if opt in ('-q','--quiet'):
                 self.verbosity = 0
             if opt in ('-v','--verbose'):
                 self.verbosity = 2
         if len(args) == 0:
             raise getopt.error("You must provide a server name.")
         server = args[0]
         args = args[1:]
         if len(args) == 0 and self.defaultTest is None:
             self.test = self.testLoader.loadTestsFromModule(self.module)
             return
         if len(args) > 0:
             self.testNames = args
         else:
             self.testNames = (self.defaultTest,)
         self.createTests()
     except getopt.error, msg:
         self.usageExit(msg)
示例#5
0
 def parseArgs(self, argv):
     global server
     import getopt
     try:
         options, args = getopt.getopt(argv[1:], 'hHvq',
                                       ['help', 'verbose', 'quiet'])
         for opt, value in options:
             if opt in ('-h', '-H', '--help'):
                 self.usageExit()
             if opt in ('-q', '--quiet'):
                 self.verbosity = 0
             if opt in ('-v', '--verbose'):
                 self.verbosity = 2
         if len(args) == 0:
             raise getopt.error("You must provide a server name.")
         server = args[0]
         args = args[1:]
         if len(args) == 0 and self.defaultTest is None:
             self.test = self.testLoader.loadTestsFromModule(self.module)
             return
         if len(args) > 0:
             self.testNames = args
         else:
             self.testNames = (self.defaultTest, )
         self.createTests()
     except getopt.error, msg:
         self.usageExit(msg)
示例#6
0
def main():
    sys.stdout = sys.stderr
    try:
        opts, rest = getopt.getopt(sys.argv[1:], 'h:p:d:qvL')
        if not rest:
            cmd = 'head'
        else:
            cmd, rest = rest[0], rest[1:]
        if cmd not in commands:
            raise getopt.error("unknown command")
        coptset, func = commands[cmd]
        copts, files = getopt.getopt(rest, coptset)
    except getopt.error as msg:
        print(msg)
        print("usage: rrcs [options] command [options] [file] ...")
        print("where command can be:")
        print("      ci|put      # checkin the given files")
        print("      co|get      # checkout")
        print("      info        # print header info")
        print("      head        # print revision of head branch")
        print("      list        # list filename if valid")
        print("      log         # print full log")
        print("      diff        # diff rcs file and work file")
        print("if no files are given, all remote rcs files are assumed")
        sys.exit(2)
    x = openrcsclient(opts)
    if not files:
        files = x.listfiles()
    for fn in files:
        try:
            func(x, copts, fn)
        except (IOError, os.error) as msg:
            print("%s: %s" % (fn, msg))
示例#7
0
def main ():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
                                   ['help', 'version', 'output-file='])
    except getopt.error(msg):
        usage(1, msg)

    outfile = None
    # parse options
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-V', '--version'):
            print >> sys.stderr, "msgfmt.py", __version__
            sys.exit(0)
        elif opt in ('-o', '--output-file'):
            outfile = arg
    # do it
    if not args:
        print >> sys.stderr, 'No input file given'
        print >> sys.stderr, "Try `msgfmt --help' for more information."
        return

    for filename in args:
        make(filename, outfile)
示例#8
0
def main():
    sys.stdout = sys.stderr
    try:
        opts, rest = getopt.getopt(sys.argv[1:], 'h:p:d:qvL')
        if not rest:
            cmd = 'head'
        else:
            cmd, rest = rest[0], rest[1:]
        if cmd not in commands:
            raise getopt.error("unknown command")
        coptset, func = commands[cmd]
        copts, files = getopt.getopt(rest, coptset)
    except getopt.error as msg:
        print(msg)
        print("usage: rrcs [options] command [options] [file] ...")
        print("where command can be:")
        print("      ci|put      # checkin the given files")
        print("      co|get      # checkout")
        print("      info        # print header info")
        print("      head        # print revision of head branch")
        print("      list        # list filename if valid")
        print("      log         # print full log")
        print("      diff        # diff rcs file and work file")
        print("if no files are given, all remote rcs files are assumed")
        sys.exit(2)
    x = openrcsclient(opts)
    if not files:
        files = x.listfiles()
    for fn in files:
        try:
            func(x, copts, fn)
        except (IOError, os.error) as msg:
            print("%s: %s" % (fn, msg))
示例#9
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "shc", 
                            ["help", "train-spam", "train-ham", "check"])
        if len(opts) == 0 or len(args) == 0:
            raise getopt.error("no options or argumens")
    except getopt.error, msg:
        print(msg)
        usage()
        sys.exit(2)
示例#10
0
文件: untabify.py 项目: xfxf/dabo
def main():
	tabsize = 8
	try:
		opts, args = getopt.getopt(sys.argv[1:], "t:")
		if not args:
			raise getopt.error("At least one file argument required")
	except getopt.error, msg:
		print msg
		print "usage:", sys.argv[0], "[-t tabwidth] file ..."
		return
示例#11
0
文件: compile.py 项目: Heimdell/lol
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])

    except getopt.error(msg):
        print(msg)
        sys.exit(2)

    for arg in args:
        print("Compiling " + arg + "... ")
        print("=========")
        compile(arg)
        print("====")
        print("done.")
def main():
    norun = False
    verbose = False
    check = False
    instlibdir = None
    reallibdir = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'vncs:')
        for o, v in opts:
            if o == '-v':
                verbose = True
            if o == '-n':
                norun = True
            if o == '-c':
                check = True
            if o == '-s':
                if not ':' in v:
                    raise getopt.error
                instlibdir, reallibdir = v.split(':')
        if len(args) != 1:
            raise getopt.error('missing arguments')
    except getopt.error:
        print 'Usage: %s [-vnc] [-s instlibdir:reallibdir] bundlepath ' % sys.argv[
            0]
        print 'Recursively slurp dylibs used in a bundle.'
        print '-n\tNo-run, only print actions, do not do the work'
        print '-v\tVerbose, print actions as well as doing them'
        print '-c\tCheck, do nothing, print nothing, return nonzero exit status if there was work'
        print '-s\tSet library directory substitution (for uninstalled libraries)'
        sys.exit(1)
    internalizer = Internalizer(os.path.realpath(args[0]), MACOSX_BUNDLE_DIRS)
    if norun:
        internalizer.norun = True
        internalizer.verbose = True
    elif verbose:
        internalizer.verbose = True
    elif check:
        internalizer.norun = True
    if instlibdir:
        internalizer.set_staging_libdir(instlibdir, reallibdir)
    internalizer.add_standard()
    internalizer.run()

    if internalizer.errors_encountered:
        print 'Errors encountered during internalization'
        sys.exit(1)
    if check:
        if internalizer.work_done:
            sys.exit(1)
示例#13
0
def option_parse(args):
    socketType = port = listeners = packSize = None    
    opts, args = getopt.getopt(args, "tup:l:s:", ["tcp", "udp" , 
"port=", "size=", "listeners="])
        
    for o, v in opts:
        if o in ("-t", "--tcp") and socketType == None:
            socketType = socket.SOCK_STREAM
        elif o in ("-u", "--udp") and socketType == None:
            socketType = socket.SOCK_DGRAM
        elif o in ("-p", "--port") and v != "" and port == None:
            port = int(v)
        elif o in ("-l", "--listeners") and v != "" and listeners == None:
            listeners = int(v)
        elif o in ("-s", "--size") and v!= "" and packSize == None:
            packSize = int(v)
        else:
            raise getopt.error("ERROR in %s, %s option" % (o, v))
    if socketType == None: raise getopt.error("SOCKET TYPE (-t or -u) is required")
    if port == None: port = DEFAULT_PORT
    if listeners == None: listeners = DEFAULT_LISTENER
    if packSize == None: packSize = DEFAULT_PACKSIZE
    
    return socketType, port, listeners, packSize
示例#14
0
def main():
    tabsize = 8
    try:
        opts, args = getopt.getopt(sys.argv[1:], "t:")
        if not args:
            raise getopt.error("At least one file argument required")
    except getopt.error as msg:
        print(msg)
        print("usage:", sys.argv[0], "[-t tabwidth] file ...")
        return
    for optname, optvalue in opts:
        if optname == '-t':
            tabsize = int(optvalue)

    for filename in args:
        process(filename, tabsize)
示例#15
0
def main():
    tabsize = 8
    try:
        opts, args = getopt.getopt(sys.argv[1:], "t:")
        if not args:
            raise getopt.error("At least one file argument required")
    except getopt.error as msg:
        print(msg)
        print("usage:", sys.argv[0], "[-t tabwidth] file ...")
        return
    for optname, optvalue in opts:
        if optname == '-t':
            tabsize = int(optvalue)

    for filename in args:
        process(filename, tabsize)
示例#16
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "")
        if len(args) > 1:
            raise getopt.error("Too many arguments.")
    except getopt.error as msg:
        usage(msg)
    for o, a in opts:
        pass
    if args:
        try:
            port = string.atoi(args[0])
        except ValueError as msg:
            usage(msg)
    else:
        port = PORT
    main_thread(port)
示例#17
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "")
        if len(args) > 1:
            raise getopt.error("Too many arguments.")
    except getopt.error as msg:
        usage(msg)
    for o, a in opts:
        pass
    if args:
        try:
            port = string.atoi(args[0])
        except ValueError as msg:
            usage(msg)
    else:
        port = PORT
    main_thread(port)
示例#18
0
def parse_args(argv):
    docs = 0
    verbosity = 1
    try:
        options, args = getopt.getopt(argv, "hH?vqd", ["help", "verbose", "quiet", "doc"])
        if args:
            raise getopt.error("no arguments accepted, got %s" % list(args))
    except getopt.error as err:
        usage_exit(err)
    for opt, value in options:
        if opt in ("-h", "-H", "-?", "--help"):
            usage_exit()
        if opt in ("-q", "--quit"):
            verbosity = 0
        if opt in ("-v", "--verbose"):
            verbosity = 2
        if opt in ("-d", "--doc"):
            docs = 1
            verbosity = 2
    return docs, verbosity
示例#19
0
def parse_args(argv):
    docs = 0
    verbosity = 1
    try:
        options, args = getopt.getopt(argv, 'hH?vqd',
                                      ['help', 'verbose', 'quiet', 'doc'])
        if args:
            raise getopt.error('no arguments accepted, got %s' % list(args))
    except getopt.error as err:
        usage_exit(err)
    for opt, value in options:
        if opt in ('-h','-H','-?','--help'):
            usage_exit()
        if opt in ('-q','--quit'):
            verbosity = 0
        if opt in ('-v', '--verbose'):
            verbosity = 2
        if opt in ('-d', '--doc'):
            docs = 1
            verbosity = 2
    return docs, verbosity
示例#20
0
def parse_args(argv):
    docs = 0
    verbosity = 1
    try:
        options, args = getopt.getopt(argv, 'hH?vqd',
                                      ['help', 'verbose', 'quiet', 'doc'])
        if args:
            raise getopt.error('no arguments accepted, got %s' % list(args))
    except getopt.error as err:
        usage_exit(err)
    for opt, value in options:
        if opt in ('-h', '-H', '-?', '--help'):
            usage_exit()
        if opt in ('-q', '--quit'):
            verbosity = 0
        if opt in ('-v', '--verbose'):
            verbosity = 2
        if opt in ('-d', '--doc'):
            docs = 1
            verbosity = 2
    return docs, verbosity
示例#21
0
def loadParameters():
    global socketClient
    try:
        opts, args = getopt.getopt(sys.argv[1:], "")
        if len(args) > 2:
            raise getopt.error("Too many arguments.")
    except getopt.error as msg:
        usage(msg)
    for o, a in opts:
        pass
    if args:
        try:
            host = args[0]
            port = int(args[1])
            socketClient = SocketClient(host, port)
            return 0
        except ValueError as msg:
            usage(msg)
            return -1
        except IndexError:
            socketClient = SocketClient('localhost', 8889)
    else:
        socketClient = SocketClient()
示例#22
0
def handleOptions():
    # set defaults
    from reportlab import rl_config
    options = {
        'cols': 2,
        'handout': 0,
        'printout': 0,
        'help': 0,
        'notes': 0,
        'fx': 1,
        'verbose': rl_config.verbose,
        'silent': 0,
        'outDir': None
    }

    args = sys.argv[1:]
    args = filter(lambda x: x and x[0] == '-', args) + filter(
        lambda x: not x or x[0] != '-', args)
    try:
        shortOpts = 'hnvsx'
        longOpts = 'cols= outdir= handout help notes printout verbose silent nofx'.split(
        )
        optList, args = getopt.getopt(args, shortOpts, longOpts)
    except getopt.error(msg):
        options['help'] = 1

    if not args and os.path.isfile('pythonpoint.xml'):
        args = ['pythonpoint.xml']

    # Remove leading dashes (max. two).
    for i in range(len(optList)):
        o, v = optList[i]
        while o[0] == '-':
            o = o[1:]
        optList[i] = (o, v)

        if o == 'cols': options['cols'] = int(v)
        elif o == 'outdir': options['outDir'] = v

    if filter(lambda ov: ov[0] == 'handout', optList):
        options['handout'] = 1

    if filter(lambda ov: ov[0] == 'printout', optList):
        options['printout'] = 1

    if optList == [] and args == [] or \
       filter(lambda ov: ov[0] in ('h', 'help'), optList):
        options['help'] = 1

    if filter(lambda ov: ov[0] in ('n', 'notes'), optList):
        options['notes'] = 1

    if filter(lambda ov: ov[0] in ('x', 'nofx'), optList):
        options['fx'] = 0

    if filter(lambda ov: ov[0] in ('v', 'verbose'), optList):
        options['verbose'] = 1

    #takes priority over verbose.  Used by our test suite etc.
    #to ensure no output at all
    if filter(lambda ov: ov[0] in ('s', 'silent'), optList):
        options['silent'] = 1
        options['verbose'] = 0

    return options, args
    for option, value in optlist:
        if option == "--help" or option == "-h":
            usage()
            sys.exit(0)
        elif option == "--number" or option == "-n":
            num = int(value)
        elif option == "--maxsize" or option == "-m":
            maxsize = int(value)
        elif option == "--percentrandom" or option == "-p":
            percent_random = float(value)
        elif option == "--tld" or option == "-t":
            tld = str(value)
        elif option == "--zonefile" or option == "-f":
            zone_file = str(value)
        else:
            getopt.error("Unknown option " + option)
except getopt.error as reason:
    sys.stderr.write(sys.argv[0] + ": " + str(reason) + "\n")
    usage()
    sys.exit(1)

if len(args) > 0:
    usage()
    sys.exit(1)

gen = random.Random()
if zone_file:
    file = open(zone_file)
    line = file.readline()
    while line:
        domain_line = domain_ns_re.match(line)
示例#24
0
  print ('</dd>')


ldap.set_option(ldap.OPT_DEBUG_LEVEL,0)

ldap._trace_level = 0

subschemasubentry_dn,schema = ldap.schema.urlfetch(sys.argv[-1],ldap.trace_level)

if subschemasubentry_dn is None:
  print ('No sub schema sub entry found!')
  sys.exit(1)

try:
  options,args=getopt.getopt(sys.argv[1:],'',['html'])
except getopt.error(e):
  print ('Error: %s\nUsage: schema_oc_tree.py [--html] [LDAP URL]')

print("----------\n")
html_output = options and options[0][0]=='--html'
oc_tree = schema.tree(ldap.schema.ObjectClass)
at_tree = schema.tree(ldap.schema.AttributeType)

#for k,v in oc_tree.items():
#  print k,'->',v
#for k,v in at_tree.items():
#  print k,'->',v

if html_output:

  print ("""<html>
from ps_parsers import *
from gml        import *
from psx        import *

uid_start    = 0
graph_cat    = gml_graph()
cluster_id   = 0
xref_file    = False
base_address = 0

# parse command line options.
try:
    opts, args = getopt.getopt(sys.argv[1:], "x:b:", ["xref=", "base="])

    if not len(args):
        raise getopt.error("no args")
except getopt.GetoptError:
    sys.stderr.write("usage: ps_graph_cat [-x <xrefs file> -b <base addr>] <file_1> [file_2] ...")
    sys.exit(1)

for o, a in opts:
    if o in ("-x", "--xref"): xref_file    = a
    if o in ("-b", "--base"): base_address = long(a, 16)

for input_file in args:
    graph_parser = gml_graph(uid_start)

    try:
        graph_parser.parse_file(input_file)
    except psx, x:
        sys.stderr.write(x.__str__())
示例#26
0
def get_opt(
        FLAG_SPEC: List[Tuple[str, str, bool, str, Any]],
        ALLOW_ACTIONS: List[str]
) -> Tuple[ List[Dict[str, Any]], Dict[str, Any] ]:

    try:
        short_opts = "".join( [t[FlagIdx.SHORT_OPT]
             + (":" if t[FlagIdx.HAS_ARG] else "") for t in FLAG_SPEC if t[FlagIdx.SHORT_OPT] is not None])
        long_opts = [t[FlagIdx.LONG_OPT] \
             + ("=" if t[FlagIdx.HAS_ARG] else "") for t in FLAG_SPEC if t[FlagIdx.LONG_OPT] is not None]

        opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
        kwargs = {}
        actions = []
        for t in FLAG_SPEC:
            # action 不加入 kwargs
            if t[FlagIdx.LONG_OPT] in ALLOW_ACTIONS:
                continue
            elif t[FlagIdx.HAS_ARG] is False:  # 不带参数的选项跳过,等后续再追加
                continue
            elif t[FlagIdx.ARG_DEFAULT_VALUE] is None:  # 要带参数的选项,如果默认参数为 None,则跳过
                continue

            # 以长参数名为 key,写入 ARG_DEFAULT_VALUE 值
            kwargs[ t[FlagIdx.LONG_OPT] ] = t[FlagIdx.ARG_DEFAULT_VALUE]

        for (opt, val) in opts:
            flag = opt.lstrip('-')
            is_long_opt = opt[:2] == '--'

            # print(f'[D]. opt={opt}, flag={flag}, val={val}')
            ok = -1
            for i, t in enumerate(FLAG_SPEC):
                if (is_long_opt and t[FlagIdx.LONG_OPT] == flag)\
                        or (not is_long_opt and t[FlagIdx.SHORT_OPT] == flag):
                    ok = i
                    break

            # print(f'is_long_opt={is_long_opt}, FLAG_SPEC[{ok}]={FLAG_SPEC[ok]}')
            if ok >= 0 and ok < len(FLAG_SPEC):
                default_value = FLAG_SPEC[ok][FlagIdx.ARG_DEFAULT_VALUE]
                action = FLAG_SPEC[ok][FlagIdx.LONG_OPT]
                value = default_value

                if FLAG_SPEC[ok][FlagIdx.HAS_ARG] == True:  # 需要带参数的,以 default_value 字段的类型转换紧跟着传入的值
                    if default_value is None:
                        value = None
                    if isinstance(default_value, int):
                        value = int(val)
                    elif isinstance(default_value, float):
                        value = float(val)
                    else:
                        value = val

                # 后面不带参数,也可以使用默认值
                if action in ALLOW_ACTIONS:
                    actions.append({action: value})
                else:
                    kwargs[action] = value

        if kwargs.get('help') is not None:
            raise getopt.error('')

        # print(f'kwargs={kwargs}', file=sys.stderr)
        # print(f'actions={actions}', file=sys.stderr)

        return actions, kwargs

    except getopt.error:
        print(get_usage(FLAG_SPEC), file=sys.stderr)
        sys.exit(1)
示例#27
0
    lexerPrint = False
    syntaxerPrint = False
    semantyxerPrint = False
    arguments, values = getopt.getopt(argumentList, unixOptions, gnuOptions)
    for arg, val in arguments:
        if arg in ['-p', '--path']:
            path = val
        elif arg in ['-l', '--lexer']:
            lexerPrint = True
        elif arg in ['-s', '--syntaxer']:
            syntaxerPrint = True
        elif arg in ['-g', '--generator']:
            semantyxerPrint = True

    if not path:
        raise getopt.error('path is required! (-p path)')

    tokens = lexer(path)['tokens']
    if lexerPrint:
        print 'TOKENS:'
        printTokens(tokens)

    syntaxer = Syntaxer(tokens)
    if syntaxerPrint:
        print 'AST:'
        syntaxer.root.view()

    if not syntaxer.error:
        Semantyxer(syntaxer.root)
        if semantyxerPrint:
            print 'ASM:'
示例#28
0
def main(argv):
  try:
    (opts, args) = getopt.getopt(argv[1:], 'a:p:o:')

    nacl_build_subarch = 0
    output_file = sys.stdout
    nacl_path = os.getcwd()

    for opt, val in opts:
      if opt == '-o':
        output_filename = val
      elif opt == '-a':
        if val.lower() == 'win32':
          nacl_build_subarch = 32
          as_exe = as32
        elif val.lower() == 'x64':
          nacl_build_subarch = 64
          as_exe = as64
        else:
          raise getopt.error('Unknown target architecture ' + val)
        # endif
      elif opt == '-p':
        nacl_path = (val)
      # endif
    # endfor

    if nacl_build_subarch == 0:
      raise getopt.error( 'You must specify a build architecture: '
                          + 'either -a Win32 or -a x64' )
    # endif

    if not output_filename:
      raise getopt.error( 'No output file specified' )
    # endif

    for filename in args:
      # normalize the filename to avoid any DOS-type funkiness
      filename = os.path.abspath(filename)
      filename = filename.replace('\\', '/')

      #
      # Run the C compiler as a preprocessor and pipe the output into a string
      #
      print >>sys.stderr, 'Preprocessing...'
      cl_env = os.environ.copy()
      cl_env['PATH'] = os.environ['PRE_WINPY_PATH']
      p = subprocess.Popen(['cl.exe',
                            '/DNACL_BLOCK_SHIFT=5'
                            '/DNACL_BUILD_ARCH=' + str(nacl_build_subarch),
                            '/DNACL_BUILD_SUBARCH=' + str(nacl_build_subarch),
                            '/DNACL_WINDOWS=1',
                            '/E',
                            '/I' + nacl_path,
                            filename],
                           env=cl_env,
                           shell=True,
                           stdout=subprocess.PIPE)
      cl_output = p.communicate()[0]

      #
      # Uncomment this if you need to see exactly what the MSVC preprocessor
      # has done to your input file.
      #print >>sys.stderr, '-------------------------------------'
      #print >>sys.stderr, '# PREPROCESSOR OUTPUT BEGINS        #'
      #print >>sys.stderr, '-------------------------------------'
      #print >>sys.stderr, cl_output
      #print >>sys.stderr, '-------------------------------------'
      #print >>sys.stderr, '# PREPROCESSOR OUTPUT ENDS          #'
      #print >>sys.stderr, '-------------------------------------'

      # GNU uses '#<linenum> for line number directives; MSVC uses
      # '#line <linenum>.'
      foo = re.compile(r'^#line ', re.MULTILINE)
      cl_output = foo.sub(r'#', cl_output)

      if p.wait() == 0: # success
        #
        # Pipe the preprocessor output into the assembler
        #
        print >>sys.stderr, 'Assembling...'
        p = subprocess.Popen([nacl_path + as_exe,
                              '-defsym','@feat.00=1',
                              '--' + str(nacl_build_subarch),
                              '-o', output_filename ],
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        as_output, as_error = p.communicate(cl_output)

        #
        # massage the assembler stderr into a format that Visual Studio likes
        #
        as_error = re.sub(r'\{standard input\}', filename, as_error)
        as_error = re.sub(r':([0-9]+):', r'(\1) :', as_error)
        as_error = re.sub(r'Error', 'error', as_error)
        as_error = re.sub(r'Warning', 'warning', as_error)

        print >>sys.stderr, as_error

      # endif
    # endfor

  except getopt.error, e:
    print >>sys.stderr, str(e)
    print >>sys.std4err, ['Usage: ',
      argv[0],
      '-a {Win32|x64} -o output_file [-p native_client_path] input_file']
            # write changes to disk
        if newLayer.SyncToDisk() != 0:
            print >>sys.stderr, 'Changes to layer "%s" could not be synced to disk' % (newLayer.GetName())
        else:
            print >>sys.stdout, 'Changes to layer "%s" successfully synced to disk' % (newLayer.GetName())

            # finshed with the datasources
    newShape = None
    oldShape = None


if __name__ == "__main__":

    try:
        # no long arguments, too lazy to implement for now...
        opts, args = getopt.getopt(sys.argv[1:], "i:o:", [])
        options = [option[0] for option in opts]
        inputs = [input[1] for input in opts]
        required = set(["-i"])
        if required.intersection(options) != required:
            raise getopt.error("Usage", "Missing required parameter")
    except getopt.GetoptError:
        Usage()
        sys.exit(2)

        # clean the file and save the output
    try:
        CleanShape(GetParam("-i", options, inputs), GetParam("-o", options, inputs, "clean"))
    except Exception as detail:
        print >>sys.stderr, "Exception: %s" % (str(detail))
示例#30
0
# -*- coding: utf-8 -*-

import sys, getopt

sys.path.append('./lexical')
sys.path.append('./syntaxer')
sys.path.append('./code_generator')

from lexical import lexical
from syntaxer import syntaxer
from code_generator import code_gen

argument_list = sys.argv[1:]

if not len(argument_list):
    raise getopt.error('path is required! (-h or --help)')

for arg in argument_list:
    if arg in ['-l', '--lexer']:
        lexical('inputFile', True)
    elif arg in ['-s', '--syntaxer']:
        syntaxer(lexical('inputFile'), True)
    elif arg in ['-g', '--generator']:
        res = syntaxer(lexical('inputFile'))
        errors = res['errors']
        parsed_tree = res['parsed_tree']
        if not len(errors):
            code_gen(parsed_tree)
    elif arg in ['-h', '--help']:
        print " -l, --lexer start lexer \n -s, --syntaxer start syntax \n -h, --help show help "
示例#31
0
def main():
	norun = False
	verbose = False
	check = False
	debug = False
	trace = False
	debug = False
	trace = False
	instlibdir = None
	reallibdir = None
	if trace:
               	print "%s: %s"%(sys._getframe().f_code.co_name,"begin")
	if trace:
               	print "%s: %s"%(sys._getframe().f_code.co_name,"begin")
	try:
		opts, args = getopt.getopt(sys.argv[1:], 'vncdts:')
		for o, v in opts:
			if o == '-v':	
				verbose = True
			if o == '-n':
				norun = True
			if o == '-c':
				check = True
			if o == '-d':
				debug = True
			if o == '-t':
				trace = True
			if o == '-s':
				if not ':' in v:
					raise getopt.error
				instlibdir, reallibdir = v.split(':')
		if len(args) != 1:
			raise getopt.error("Must specify bundlepath only.")
	except getopt.error:
		print 'Usage: %s [-vnc] [-s instlibdir:reallibdir] bundlepath '% sys.argv[0]
		print 'Recursively slurp dylibs used in a bundle.'
		print '-n\tNo-run, only print actions, do not do the work'
		print '-v\tVerbose, print actions as well as doing them'
		print '-c\tCheck, do nothing, print nothing, return nonzero exit status if there was work'
		print '-s\tSet library directory substitution (for uninstalled libraries)'
		print '-t\tTrace, print each function name and arguments when called '
		print '-d\tDebug, print a lot of detailed information, e.g. to debug this script'
		sys.exit(1)
	internalizer = Internalizer(os.path.realpath(args[0]), LINUX_BUNDLE_DIRS)
	if norun:
		internalizer.norun = True
		internalizer.verbose = True
	elif verbose:
		internalizer.verbose = True
	elif check:
		internalizer.norun = True
	if debug:
        	if verbose:
			internalizer.verbose = True
		internalizer.debug = True
	if debug:
        	if verbose:
			internalizer.verbose = True
		internalizer.debug = True
		
	if trace:
        	if verbose:
			internalizer.verbose = True
		internalizer.trace = True

	if trace:
        	if verbose:
			internalizer.verbose = True
		internalizer.trace = True

	internalizer.add_standard()
	internalizer.run()
	
	if check:
		if internalizer.work_done:
			sys.exit(1)
示例#32
0
        try:
                value = inputs[options.index(optionName)]
                return value if value != '' else default
        except:
                return default

if __name__ == '__main__':

        try:
                #no long arguments, too lazy to implement for now...
                opts, args = getopt.getopt(sys.argv[1:], "c:f:v:", [])
                options = [option[0] for option in opts]
                inputs = [input[1] for input in opts]
                required = set(['-c', '-f'])
                if required.intersection(options) != required:
                        raise getopt.error('Usage', 'Missing required parameter')
        except getopt.GetoptError:
                Usage()
                sys.exit(2)

	#get the storage object
	storage = load(GetParam('-c', options, inputs))

	#get the verbosity
	try:
		verbosity = int(GetParam('-v', options, inputs))
	except:
		verbosity = None

	#for each line
	count = 0
示例#33
0
 def handle_option(self, opt, val):
     raise getopt.error("option %s not recognized" % opt)
示例#34
0
    'us' : USpaper, 'usr' : USRpaper }

paperdef = A4Rpaper

try:
    optlist, args = getopt.getopt(sys.argv[1:], "nkt:")
    for opt, arg in optlist:
	if opt == '-n':
	    nodeflag = 1
	if opt == '-k':
	    knownflag = 1
	if opt == '-t':
	    if arg in papertypes:
		paperdef = papertypes[arg]
	    else:
		raise getopt.error("unknown paper type '%s'" % arg)

except getopt.error as msg:
    sys.stderr.write("%s: %s\n" % (__scriptname, msg))
    printusage()
    sys.exit(1)

if len(args) != 1:
    printusage()
    sys.exit(1)

filename = args[0]

profile = open(filename).readlines()

# Build the call tree.
示例#35
0
def main(args=None):
    prefs = grailbase.GrailPrefs.AllPreferences()
    # XXX Disable cache for NT
    if sys.platform == 'win32':
        prefs.Set('disk-cache', 'size', '0')
    global ilu_tk
    ilu_tk = 0
    if prefs.GetBoolean('security', 'enable-ilu'):
        try:
            import ilu_tk
        except ImportError:
            pass
    if args is not None:
        embedded = 1
    else:
        args = sys.argv[1:]
        embedded = 0
    try:
        opts, args = getopt.getopt(args, 'd:g:iq',
                                   ['display=', 'geometry=', 'noimages'])
        if len(args) > 1:
            raise getopt.error("too many arguments")
    except getopt.error as msg:
        sys.stdout = sys.stderr
        print("Command line error:", msg)
        print(USAGE)
        sys.exit(2)

    geometry = prefs.Get('browser', 'initial-geometry')
    display = None
    user_init = 1

    for o, a in opts:
        if o in ('-i', '--noimages'):
            load_images = 0
        if o in ('-g', '--geometry'):
            geometry = a
        if o in ('-d', '--display'):
            display = a
        if o == "-q":
            user_init = 0
    if args:
        url = grailutil.complete_url(args[0])
    else:
        url = None
    global app
    app = Application(prefs=prefs, display=display)
    app.embedded = embedded
    if __name__ != '__main__':
        import __main__
        __main__.app = app
        __main__.GRAILVERSION = GRAILVERSION

    def load_images_vis_prefs(app=app):
        app.load_images = app.prefs.GetBoolean('browser', 'load-images')

    try:
        app.load_images = load_images
    except NameError:
        load_images_vis_prefs()
    prefs.AddGroupCallback('browser', load_images_vis_prefs)

    from utils import Safetkinter
    Safetkinter._castrate(app.root.tk)

    tktools.install_keybindings(app.root)

    # Make everybody who's still using urllib.urlopen go through the cache
    urllib.urlopen = app.open_url_simple

    # Add $GRAILDIR/user/ to sys.path
    subdir = os.path.join(app.graildir, 'user')
    if subdir not in sys.path:
        sys.path.insert(0, subdir)

    # Import user's grail startup file, defined as
    # $GRAILDIR/user/grailrc.py if it exists.
    if user_init:
        try:
            from SampleGrailDir import grailrc
        except ImportError as e:
            # Only catch this if grailrc itself doesn't import,
            # otherwise propogate.
            if str.split(e.args[0])[-1] != "grailrc":
                raise
        except:
            app.exception_dialog('during import of startup file')

    # Load the initial page (command line argument or from preferences)
    if not embedded:
        from Browser import Browser
        browser = Browser(app.root, app, geometry=geometry)
        if url:
            browser.context.load(url)
        elif prefs.GetBoolean('browser', 'load-initial-page'):
            browser.home_command()

    if not embedded:
        # Give the user control
        app.go()
    long_options = ["base =", "recursive ="]
    try:
        # Parsing argument
        arguments, values = getopt.getopt(argumentList, options, long_options)

        # Checking each argument with options
        for currentArgument, currentValue in arguments:

            if currentArgument in ("-b", "--base"):
                arg_dict["base_value"] = int(currentValue)
            elif currentArgument in ("-r", "--recursive"):
                arg_dict["recursive"] = int(currentValue)

        # Check rest of the arguments
        if len(values) < 4:
            raise getopt.error("Required arguments were not given correctly")
        arg_dict["method"] = values[0]
        arg_dict["input_file_name"] = values[1]
        arg_dict["encoding"] = values[2]
        arg_dict["output_file_name"] = values[3]

        # Call method with arguments passed as parameters
        if arg_dict["method"] == "encode":
            result = encode(file_name=arg_dict["input_file_name"],
                            output_name=arg_dict["output_file_name"],
                            encoding=arg_dict["encoding"],
                            base_value=arg_dict["base_value"])
            for i in range(arg_dict["recursive"] - 1):
                result = encode(file_name=arg_dict["output_file_name"],
                                output_name=arg_dict["output_file_name"],
                                encoding=arg_dict["encoding"],
示例#37
0
if __name__ == '__main__':
    try:
        (opts, args) = getopt.getopt(sys.argv[1:], "htg")

        mode = "gui"
        for opt, arg in opts:
            if opt == '-t':
                mode = "text"
            elif opt == '-g':
                mode = "gui"
            elif opt == '-h':
                usage()
                sys.exit(0)

        if not args:
            raise getopt.error("no kickstart files given")
        
        for fileName in args:
            #
            # Populate the userchoices singleton.
            #
            fauxroot.FAUXROOT = [os.path.join(TEST_DIR, "good-config.1")]
            si = test_scriptedinstall.ScriptedInstallPreparser(fileName)
            (result, errors, warnings) = si.preParse()
            if result == test_scriptedinstall.Result.FAIL:
                print "result=", result
                print '\n'.join(errors)
                print '\n'.join(warnings)
                fauxroot.FAUXROOT = None
                continue
from ps_parsers import *
from gml        import *
from psx        import *

uid_start    = 0
graph_cat    = gml_graph()
cluster_id   = 0
xref_file    = False
base_address = 0

# parse command line options.
try:
    opts, args = getopt.getopt(sys.argv[1:], "x:b:", ["xref=", "base="])

    if not len(args):
        raise getopt.error("no args")
except getopt.GetoptError:
    sys.stderr.write("usage: ps_graph_cat [-x <xrefs file> -b <base addr>] <file_1> [file_2] ...")
    sys.exit(1)

for o, a in opts:
    if o in ("-x", "--xref"): xref_file    = a
    if o in ("-b", "--base"): base_address = long(a, 16)

for input_file in args:
    graph_parser = gml_graph(uid_start)

    try:
        graph_parser.parse_file(input_file)
    except psx, x:
        sys.stderr.write(x.__str__())
示例#39
0
 def handle_option(self, opt, val):
     raise getopt.error("option %s not recognized" % opt)
示例#40
0
    for option, value in optlist:
        if option == "--help" or option == "-h":
            usage()
            sys.exit(0)
        elif option == "--number" or option == "-n":
            num = int(value)
        elif option == "--maxsize" or option == "-m":
            maxsize = int(value)
        elif option == "--percentrandom" or option == "-p":
            percent_random = float(value)
        elif option == "--tld" or option == "-t":
            tld = str(value)
        elif option == "--zonefile" or option == "-f":
            zone_file = str(value)
        else:
            getopt.error("Unknown option " + option)
except getopt.error as reason:
    sys.stderr.write(sys.argv[0] + ": " + str(reason) + "\n")
    usage()
    sys.exit(1)

if len(args) > 0:
    usage()
    sys.exit(1)

gen = random.Random()
if zone_file:
    file = open(zone_file)
    line = file.readline()
    while line:
        domain_line = domain_ns_re.match(line)
示例#41
0
def main(argv):
  try:
    (opts, args) = getopt.getopt(argv[1:], 'a:p:o:')

    nacl_build_subarch = 0
    nacl_path = os.getcwd()
    output_filename = None

    for opt, val in opts:
      if opt == '-o':
        output_filename = val
      elif opt == '-a':
        if val.lower() == 'win32':
          nacl_build_arch = 'x86'
          nacl_build_subarch = 32
          as_exe = as32
        elif val.lower() == 'x64':
          nacl_build_arch = 'x86'
          nacl_build_subarch = 64
          as_exe = as64
        else:
          raise getopt.error('Unknown target architecture ' + val)
      elif opt == '-p':
        nacl_path = (val)

    if nacl_build_subarch == 0:
      raise getopt.error( 'You must specify a build architecture: '
                          + 'either -a Win32 or -a x64' )

    if output_filename is None:
      raise getopt.error( 'No output file specified' )

    for filename in args:
      # normalize the filename to avoid any DOS-type funkiness
      filename = os.path.abspath(filename)
      filename = filename.replace('\\', '/')

      #
      # Run the C compiler as a preprocessor and pipe the output into a string
      #
      cl_command = ['cl.exe',
                    '/nologo',
                    '/D__ASSEMBLER__',
                    '/DNACL_BUILD_ARCH=' + nacl_build_arch,
                    '/DNACL_BUILD_SUBARCH=' + str(nacl_build_subarch),
                    '/DNACL_WINDOWS=1',
                    '/TP',
                    '/E',
                    '/I' + nacl_path,
                    filename]
      p = subprocess.Popen(cl_command,
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
      cl_results = p.communicate()
      cl_status = p.returncode
      cl_output = cl_results[0]
      cl_errors = cl_results[1]

      if cl_status != 0:
        print(
            'FAILED: %s\n%s\n' % (' '.join(cl_command), cl_errors),
            file=sys.stderr)
        return cl_status

      #
      # Uncomment this if you need to see exactly what the MSVC preprocessor
      # has done to your input file.
      #print('-------------------------------------', file=sys.stderr)
      #print('# PREPROCESSOR OUTPUT BEGINS        #', file=sys.stderr)
      #print('-------------------------------------', file=sys.stderr)
      #print(cl_output, file=sys.stderr)
      #print('-------------------------------------', file=sys.stderr)
      #print('# PREPROCESSOR OUTPUT ENDS          #', file=sys.stderr)
      #print('-------------------------------------', file=sys.stderr)

      # GNU uses '#<linenum> for line number directives; MSVC uses
      # '#line <linenum>.'
      foo = re.compile(br'^#line ', re.MULTILINE)
      cl_output = foo.sub(br'#', cl_output)

      #
      # Pipe the preprocessor output into the assembler
      #
      as_command = [nacl_path + as_exe,
                    '-defsym','@feat.00=1',
                    '--' + str(nacl_build_subarch),
                    '-o', output_filename]
      p = subprocess.Popen(as_command,
                           stdin=subprocess.PIPE,
                           stderr=subprocess.PIPE)
      as_output, as_error = p.communicate(cl_output)
      as_status = p.returncode

      #
      # massage the assembler stderr into a format that Visual Studio likes
      #
      as_error = re.sub(br'\{standard input\}', filename, as_error)
      as_error = re.sub(br':([0-9]+):', r'(\1) :', as_error)
      as_error = re.sub(br'Error', 'error', as_error)
      as_error = re.sub(br'Warning', 'warning', as_error)

      if as_error:
        print(as_error, file=sys.stderr)

      if as_status != 0:
        print('FAILED: %s\n' % ' '.join(as_command), file=sys.stderr)
        return as_status

  except getopt.error as e:
    print(str(e), file=sys.stderr)
    print(
        'Usage: ',
        argv[0],
        '-a {Win32|x64} -o output_file [-p native_client_path] input_file',
        file=sys.stderr)
示例#42
0
def main(argv):
    try:
        (opts, args) = getopt.getopt(argv[1:], 'a:p:o:')

        nacl_build_subarch = 0
        output_file = sys.stdout
        nacl_path = os.getcwd()

        for opt, val in opts:
            if opt == '-o':
                output_filename = val
            elif opt == '-a':
                if val.lower() == 'win32':
                    nacl_build_subarch = 32
                    as_exe = as32
                elif val.lower() == 'x64':
                    nacl_build_subarch = 64
                    as_exe = as64
                else:
                    raise getopt.error('Unknown target architecture ' + val)
                # endif
            elif opt == '-p':
                nacl_path = (val)
            # endif
        # endfor

        if nacl_build_subarch == 0:
            raise getopt.error('You must specify a build architecture: ' +
                               'either -a Win32 or -a x64')
        # endif

        if not output_filename:
            raise getopt.error('No output file specified')
        # endif

        for filename in args:
            # normalize the filename to avoid any DOS-type funkiness
            filename = os.path.abspath(filename)
            filename = filename.replace('\\', '/')

            #
            # Run the C compiler as a preprocessor and pipe the output into a string
            #
            print >> sys.stderr, 'Preprocessing...'
            cl_env = os.environ.copy()
            cl_env['PATH'] = os.environ['PRE_WINPY_PATH']
            p = subprocess.Popen([
                'cl.exe', '/DNACL_BLOCK_SHIFT=5'
                '/DNACL_BUILD_ARCH=' + str(nacl_build_subarch),
                '/DNACL_BUILD_SUBARCH=' + str(nacl_build_subarch),
                '/DNACL_WINDOWS=1', '/E', '/I' + nacl_path, filename
            ],
                                 env=cl_env,
                                 shell=True,
                                 stdout=subprocess.PIPE)
            cl_output = p.communicate()[0]

            #
            # Uncomment this if you need to see exactly what the MSVC preprocessor
            # has done to your input file.
            #print >>sys.stderr, '-------------------------------------'
            #print >>sys.stderr, '# PREPROCESSOR OUTPUT BEGINS        #'
            #print >>sys.stderr, '-------------------------------------'
            #print >>sys.stderr, cl_output
            #print >>sys.stderr, '-------------------------------------'
            #print >>sys.stderr, '# PREPROCESSOR OUTPUT ENDS          #'
            #print >>sys.stderr, '-------------------------------------'

            # GNU uses '#<linenum> for line number directives; MSVC uses
            # '#line <linenum>.'
            foo = re.compile(r'^#line ', re.MULTILINE)
            cl_output = foo.sub(r'#', cl_output)

            if p.wait() == 0:  # success
                #
                # Pipe the preprocessor output into the assembler
                #
                print >> sys.stderr, 'Assembling...'
                p = subprocess.Popen([
                    nacl_path + as_exe, '-defsym', '@feat.00=1',
                    '--' + str(nacl_build_subarch), '-o', output_filename
                ],
                                     stdin=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
                as_output, as_error = p.communicate(cl_output)

                #
                # massage the assembler stderr into a format that Visual Studio likes
                #
                as_error = re.sub(r'\{standard input\}', filename, as_error)
                as_error = re.sub(r':([0-9]+):', r'(\1) :', as_error)
                as_error = re.sub(r'Error', 'error', as_error)
                as_error = re.sub(r'Warning', 'warning', as_error)

                print >> sys.stderr, as_error

            # endif
        # endfor

    except getopt.error, e:
        print >> sys.stderr, str(e)
        print >> sys.std4err, [
            'Usage: ', argv[0],
            '-a {Win32|x64} -o output_file [-p native_client_path] input_file'
        ]
示例#43
0
def main(argv):
    try:
        (opts, args) = getopt.getopt(argv[1:], "a:p:o:")

        nacl_build_subarch = 0
        nacl_path = os.getcwd()
        output_filename = None

        for opt, val in opts:
            if opt == "-o":
                output_filename = val
            elif opt == "-a":
                if val.lower() == "win32":
                    nacl_build_arch = "x86"
                    nacl_build_subarch = 32
                    as_exe = as32
                elif val.lower() == "x64":
                    nacl_build_arch = "x86"
                    nacl_build_subarch = 64
                    as_exe = as64
                else:
                    raise getopt.error("Unknown target architecture " + val)
                # endif
            elif opt == "-p":
                nacl_path = val
            # endif
        # endfor

        if nacl_build_subarch == 0:
            raise getopt.error("You must specify a build architecture: " + "either -a Win32 or -a x64")
        # endif

        if output_filename is None:
            raise getopt.error("No output file specified")
        # endif

        for filename in args:
            # normalize the filename to avoid any DOS-type funkiness
            filename = os.path.abspath(filename)
            filename = filename.replace("\\", "/")

            #
            # Run the C compiler as a preprocessor and pipe the output into a string
            #
            p = subprocess.Popen(
                [
                    "cl.exe",
                    "/nologo",
                    "/D__ASSEMBLER__",
                    "/DNACL_BUILD_ARCH=" + nacl_build_arch,
                    "/DNACL_BUILD_SUBARCH=" + str(nacl_build_subarch),
                    "/DNACL_WINDOWS=1",
                    "/TP",
                    "/E",
                    "/I" + nacl_path,
                    filename,
                ],
                shell=True,
                stdout=subprocess.PIPE,
                stderr=open(os.devnull, "w"),
            )
            cl_output = p.communicate()[0]

            #
            # Uncomment this if you need to see exactly what the MSVC preprocessor
            # has done to your input file.
            # print >>sys.stderr, '-------------------------------------'
            # print >>sys.stderr, '# PREPROCESSOR OUTPUT BEGINS        #'
            # print >>sys.stderr, '-------------------------------------'
            # print >>sys.stderr, cl_output
            # print >>sys.stderr, '-------------------------------------'
            # print >>sys.stderr, '# PREPROCESSOR OUTPUT ENDS          #'
            # print >>sys.stderr, '-------------------------------------'

            # GNU uses '#<linenum> for line number directives; MSVC uses
            # '#line <linenum>.'
            foo = re.compile(r"^#line ", re.MULTILINE)
            cl_output = foo.sub(r"#", cl_output)

            if p.wait() == 0:  # success
                #
                # Pipe the preprocessor output into the assembler
                #
                p = subprocess.Popen(
                    [
                        nacl_path + as_exe,
                        "-defsym",
                        "@feat.00=1",
                        "--" + str(nacl_build_subarch),
                        "-o",
                        output_filename,
                    ],
                    stdin=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                as_output, as_error = p.communicate(cl_output)

                #
                # massage the assembler stderr into a format that Visual Studio likes
                #
                as_error = re.sub(r"\{standard input\}", filename, as_error)
                as_error = re.sub(r":([0-9]+):", r"(\1) :", as_error)
                as_error = re.sub(r"Error", "error", as_error)
                as_error = re.sub(r"Warning", "warning", as_error)

                if as_error:
                    print >>sys.stderr, as_error

            # endif
        # endfor

    except getopt.error, e:
        print >>sys.stderr, str(e)
        print >>sys.stderr, ["Usage: ", argv[0], "-a {Win32|x64} -o output_file [-p native_client_path] input_file"]
示例#44
0
def main(argv):
  try:
    (opts, args) = getopt.getopt(argv[1:], 'a:p:o:')

    nacl_build_subarch = 0
    nacl_path = os.getcwd()
    output_filename = None

    for opt, val in opts:
      if opt == '-o':
        output_filename = val
      elif opt == '-a':
        if val.lower() == 'win32':
          nacl_build_arch = 'x86'
          nacl_build_subarch = 32
          as_exe = as32
        elif val.lower() == 'x64':
          nacl_build_arch = 'x86'
          nacl_build_subarch = 64
          as_exe = as64
        else:
          raise getopt.error('Unknown target architecture ' + val)
      elif opt == '-p':
        nacl_path = (val)

    if nacl_build_subarch == 0:
      raise getopt.error( 'You must specify a build architecture: '
                          + 'either -a Win32 or -a x64' )

    if output_filename is None:
      raise getopt.error( 'No output file specified' )

    for filename in args:
      # normalize the filename to avoid any DOS-type funkiness
      filename = os.path.abspath(filename)
      filename = filename.replace('\\', '/')

      #
      # Run the C compiler as a preprocessor and pipe the output into a string
      #
      cl_command = ['cl.exe',
                    '/nologo',
                    '/D__ASSEMBLER__',
                    '/DNACL_BUILD_ARCH=' + nacl_build_arch,
                    '/DNACL_BUILD_SUBARCH=' + str(nacl_build_subarch),
                    '/DNACL_WINDOWS=1',
                    '/TP',
                    '/E',
                    '/I' + nacl_path,
                    filename]
      p = subprocess.Popen(cl_command,
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
      cl_results = p.communicate()
      cl_status = p.returncode
      cl_output = cl_results[0]
      cl_errors = cl_results[1]

      if cl_status != 0:
        print >>sys.stderr, 'FAILED: %s\n%s\n' % (' '.join(cl_command),
                                                  cl_errors)
        return cl_status

      #
      # Uncomment this if you need to see exactly what the MSVC preprocessor
      # has done to your input file.
      #print >>sys.stderr, '-------------------------------------'
      #print >>sys.stderr, '# PREPROCESSOR OUTPUT BEGINS        #'
      #print >>sys.stderr, '-------------------------------------'
      #print >>sys.stderr, cl_output
      #print >>sys.stderr, '-------------------------------------'
      #print >>sys.stderr, '# PREPROCESSOR OUTPUT ENDS          #'
      #print >>sys.stderr, '-------------------------------------'

      # GNU uses '#<linenum> for line number directives; MSVC uses
      # '#line <linenum>.'
      foo = re.compile(r'^#line ', re.MULTILINE)
      cl_output = foo.sub(r'#', cl_output)

      #
      # Pipe the preprocessor output into the assembler
      #
      as_command = [nacl_path + as_exe,
                    '-defsym','@feat.00=1',
                    '--' + str(nacl_build_subarch),
                    '-o', output_filename]
      p = subprocess.Popen(as_command,
                           stdin=subprocess.PIPE,
                           stderr=subprocess.PIPE)
      as_output, as_error = p.communicate(cl_output)
      as_status = p.returncode

      #
      # massage the assembler stderr into a format that Visual Studio likes
      #
      as_error = re.sub(r'\{standard input\}', filename, as_error)
      as_error = re.sub(r':([0-9]+):', r'(\1) :', as_error)
      as_error = re.sub(r'Error', 'error', as_error)
      as_error = re.sub(r'Warning', 'warning', as_error)

      if as_error:
        print >>sys.stderr, as_error

      if as_status != 0:
        print >>sys.stderr, 'FAILED: %s\n' % ' '.join(as_command)
        return as_status

  except getopt.error, e:
    print >>sys.stderr, str(e)
    print >>sys.stderr, ['Usage: ',
      argv[0],
      '-a {Win32|x64} -o output_file [-p native_client_path] input_file']
示例#45
0
文件: brandiso.py 项目: vmware/weasel
    print "  $ %s -c newiso.iso" % argv[0]
    print "  My ISO v1.0: OK"
    
#
# init code
#

fill_fields()

if __name__ == '__main__':

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hvb:clz")

        if len(args) != 1:
            raise getopt.error("expecting ISO path")

        isoPath = args[0]

        modeFunction = None
        for opt, arg in opts:
            if opt == "-h":
                usage()
                sys.exit()
            elif opt == "-v":
                VERBOSE += 1
            elif opt == "-b":
                _id_off, id_len, _ = fields[ID_FIELD]
                if len(arg) > id_len:
                    raise getopt.error(
                        "volume identifier must be <= %d characters" % id_len)
示例#46
0
def handleOptions():
    # set defaults
    from reportlab import rl_config
    options = {'cols':2,
               'handout':0,
               'printout':0,
               'help':0,
               'notes':0,
               'fx':1,
               'verbose':rl_config.verbose,
               'silent':0,
               'outDir': None}

    args = sys.argv[1:]
    args = filter(lambda x: x and x[0]=='-',args) + filter(lambda x: not x or x[0]!='-',args)
    try:
        shortOpts = 'hnvsx'
        longOpts = 'cols= outdir= handout help notes printout verbose silent nofx'.split()
        optList, args = getopt.getopt(args, shortOpts, longOpts)
    except getopt.error(msg):
        options['help'] = 1

    if not args and os.path.isfile('pythonpoint.xml'):
        args = ['pythonpoint.xml']

    # Remove leading dashes (max. two).
    for i in range(len(optList)):
        o, v = optList[i]
        while o[0] == '-':
            o = o[1:]
        optList[i] = (o, v)

        if o == 'cols': options['cols'] = int(v)
        elif o=='outdir': options['outDir'] = v

    if filter(lambda ov: ov[0] == 'handout', optList):
        options['handout'] = 1

    if filter(lambda ov: ov[0] == 'printout', optList):
        options['printout'] = 1

    if optList == [] and args == [] or \
       filter(lambda ov: ov[0] in ('h', 'help'), optList):
        options['help'] = 1

    if filter(lambda ov: ov[0] in ('n', 'notes'), optList):
        options['notes'] = 1

    if filter(lambda ov: ov[0] in ('x', 'nofx'), optList):
        options['fx'] = 0

    if filter(lambda ov: ov[0] in ('v', 'verbose'), optList):
        options['verbose'] = 1

    #takes priority over verbose.  Used by our test suite etc.
        #to ensure no output at all
    if filter(lambda ov: ov[0] in ('s', 'silent'), optList):
        options['silent'] = 1
        options['verbose'] = 0


    return options, args