CmdLine.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #
  2. # Cython - Command Line Parsing
  3. #
  4. from __future__ import absolute_import
  5. import os
  6. import sys
  7. from . import Options
  8. usage = """\
  9. Cython (http://cython.org) is a compiler for code written in the
  10. Cython language. Cython is based on Pyrex by Greg Ewing.
  11. Usage: cython [options] sourcefile.{pyx,py} ...
  12. Options:
  13. -V, --version Display version number of cython compiler
  14. -l, --create-listing Write error messages to a listing file
  15. -I, --include-dir <directory> Search for include files in named directory
  16. (multiple include directories are allowed).
  17. -o, --output-file <filename> Specify name of generated C file
  18. -t, --timestamps Only compile newer source files
  19. -f, --force Compile all source files (overrides implied -t)
  20. -v, --verbose Be verbose, print file names on multiple compilation
  21. -p, --embed-positions If specified, the positions in Cython files of each
  22. function definition is embedded in its docstring.
  23. --cleanup <level> Release interned objects on python exit, for memory debugging.
  24. Level indicates aggressiveness, default 0 releases nothing.
  25. -w, --working <directory> Sets the working directory for Cython (the directory modules
  26. are searched from)
  27. --gdb Output debug information for cygdb
  28. --gdb-outdir <directory> Specify gdb debug information output directory. Implies --gdb.
  29. -D, --no-docstrings Strip docstrings from the compiled module.
  30. -a, --annotate Produce a colorized HTML version of the source.
  31. --annotate-coverage <cov.xml> Annotate and include coverage information from cov.xml.
  32. --line-directives Produce #line directives pointing to the .pyx source
  33. --cplus Output a C++ rather than C file.
  34. --embed[=<method_name>] Generate a main() function that embeds the Python interpreter.
  35. -2 Compile based on Python-2 syntax and code semantics.
  36. -3 Compile based on Python-3 syntax and code semantics.
  37. --3str Compile based on Python-3 syntax and code semantics without
  38. assuming unicode by default for string literals under Python 2.
  39. --lenient Change some compile time errors to runtime errors to
  40. improve Python compatibility
  41. --capi-reexport-cincludes Add cincluded headers to any auto-generated header files.
  42. --fast-fail Abort the compilation on the first error
  43. --warning-errors, -Werror Make all warnings into errors
  44. --warning-extra, -Wextra Enable extra warnings
  45. -X, --directive <name>=<value>[,<name=value,...] Overrides a compiler directive
  46. -E, --compile-time-env name=value[,<name=value,...] Provides compile time env like DEF would do.
  47. """
  48. # The following experimental options are supported only on MacOSX:
  49. # -C, --compile Compile generated .c file to .o file
  50. # --link Link .o file to produce extension module (implies -C)
  51. # -+, --cplus Use C++ compiler for compiling and linking
  52. # Additional .o files to link may be supplied when using -X."""
  53. def bad_usage():
  54. sys.stderr.write(usage)
  55. sys.exit(1)
  56. def parse_command_line(args):
  57. from .Main import CompilationOptions, default_options
  58. pending_arg = []
  59. def pop_arg():
  60. if not args or pending_arg:
  61. bad_usage()
  62. if '=' in args[0] and args[0].startswith('--'): # allow "--long-option=xyz"
  63. name, value = args.pop(0).split('=', 1)
  64. pending_arg.append(value)
  65. return name
  66. return args.pop(0)
  67. def pop_value(default=None):
  68. if pending_arg:
  69. return pending_arg.pop()
  70. elif default is not None:
  71. return default
  72. elif not args:
  73. bad_usage()
  74. return args.pop(0)
  75. def get_param(option):
  76. tail = option[2:]
  77. if tail:
  78. return tail
  79. else:
  80. return pop_arg()
  81. options = CompilationOptions(default_options)
  82. sources = []
  83. while args:
  84. if args[0].startswith("-"):
  85. option = pop_arg()
  86. if option in ("-V", "--version"):
  87. options.show_version = 1
  88. elif option in ("-l", "--create-listing"):
  89. options.use_listing_file = 1
  90. elif option in ("-+", "--cplus"):
  91. options.cplus = 1
  92. elif option == "--embed":
  93. Options.embed = pop_value("main")
  94. elif option.startswith("-I"):
  95. options.include_path.append(get_param(option))
  96. elif option == "--include-dir":
  97. options.include_path.append(pop_value())
  98. elif option in ("-w", "--working"):
  99. options.working_path = pop_value()
  100. elif option in ("-o", "--output-file"):
  101. options.output_file = pop_value()
  102. elif option in ("-t", "--timestamps"):
  103. options.timestamps = 1
  104. elif option in ("-f", "--force"):
  105. options.timestamps = 0
  106. elif option in ("-v", "--verbose"):
  107. options.verbose += 1
  108. elif option in ("-p", "--embed-positions"):
  109. Options.embed_pos_in_docstring = 1
  110. elif option in ("-z", "--pre-import"):
  111. Options.pre_import = pop_value()
  112. elif option == "--cleanup":
  113. Options.generate_cleanup_code = int(pop_value())
  114. elif option in ("-D", "--no-docstrings"):
  115. Options.docstrings = False
  116. elif option in ("-a", "--annotate"):
  117. Options.annotate = True
  118. elif option == "--annotate-coverage":
  119. Options.annotate = True
  120. Options.annotate_coverage_xml = pop_value()
  121. elif option == "--convert-range":
  122. Options.convert_range = True
  123. elif option == "--line-directives":
  124. options.emit_linenums = True
  125. elif option == "--no-c-in-traceback":
  126. options.c_line_in_traceback = False
  127. elif option == "--gdb":
  128. options.gdb_debug = True
  129. options.output_dir = os.curdir
  130. elif option == "--gdb-outdir":
  131. options.gdb_debug = True
  132. options.output_dir = pop_value()
  133. elif option == "--lenient":
  134. Options.error_on_unknown_names = False
  135. Options.error_on_uninitialized = False
  136. elif option == '-2':
  137. options.language_level = 2
  138. elif option == '-3':
  139. options.language_level = 3
  140. elif option == '--3str':
  141. options.language_level = '3str'
  142. elif option == "--capi-reexport-cincludes":
  143. options.capi_reexport_cincludes = True
  144. elif option == "--fast-fail":
  145. Options.fast_fail = True
  146. elif option == "--cimport-from-pyx":
  147. Options.cimport_from_pyx = True
  148. elif option in ('-Werror', '--warning-errors'):
  149. Options.warning_errors = True
  150. elif option in ('-Wextra', '--warning-extra'):
  151. options.compiler_directives.update(Options.extra_warnings)
  152. elif option == "--old-style-globals":
  153. Options.old_style_globals = True
  154. elif option == "--directive" or option.startswith('-X'):
  155. if option.startswith('-X') and option[2:].strip():
  156. x_args = option[2:]
  157. else:
  158. x_args = pop_value()
  159. try:
  160. options.compiler_directives = Options.parse_directive_list(
  161. x_args, relaxed_bool=True,
  162. current_settings=options.compiler_directives)
  163. except ValueError as e:
  164. sys.stderr.write("Error in compiler directive: %s\n" % e.args[0])
  165. sys.exit(1)
  166. elif option == "--compile-time-env" or option.startswith('-E'):
  167. if option.startswith('-E') and option[2:].strip():
  168. x_args = option[2:]
  169. else:
  170. x_args = pop_value()
  171. try:
  172. options.compile_time_env = Options.parse_compile_time_env(
  173. x_args, current_settings=options.compile_time_env)
  174. except ValueError as e:
  175. sys.stderr.write("Error in compile-time-env: %s\n" % e.args[0])
  176. sys.exit(1)
  177. elif option.startswith('--debug'):
  178. option = option[2:].replace('-', '_')
  179. from . import DebugFlags
  180. if option in dir(DebugFlags):
  181. setattr(DebugFlags, option, True)
  182. else:
  183. sys.stderr.write("Unknown debug flag: %s\n" % option)
  184. bad_usage()
  185. elif option in ('-h', '--help'):
  186. sys.stdout.write(usage)
  187. sys.exit(0)
  188. else:
  189. sys.stderr.write("Unknown compiler flag: %s\n" % option)
  190. sys.exit(1)
  191. else:
  192. sources.append(pop_arg())
  193. if pending_arg:
  194. bad_usage()
  195. if options.use_listing_file and len(sources) > 1:
  196. sys.stderr.write(
  197. "cython: Only one source file allowed when using -o\n")
  198. sys.exit(1)
  199. if len(sources) == 0 and not options.show_version:
  200. bad_usage()
  201. if Options.embed and len(sources) > 1:
  202. sys.stderr.write(
  203. "cython: Only one source file allowed when using -embed\n")
  204. sys.exit(1)
  205. return options, sources