本文整理汇总了Python中Cython.Compiler.Main.CompilationOptions类的典型用法代码示例。如果您正苦于以下问题:Python CompilationOptions类的具体用法?Python CompilationOptions怎么用?Python CompilationOptions使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CompilationOptions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cythonize
def cythonize(source, includes=(),
output_h=os.curdir):
name, ext = os.path.splitext(source)
output_c = name + '.c'
#
from Cython.Compiler.Main import \
CompilationOptions, default_options, \
compile, \
PyrexError
#
options = CompilationOptions(default_options)
options.output_file = output_c
options.include_path = includes
#
from Cython.Compiler import Options
Options.generate_cleanup_code = 3
#
any_failures = 0
try:
result = compile(source, options)
if result.num_errors > 0:
any_failures = 1
except (EnvironmentError, PyrexError), e:
sys.stderr.write(str(e) + '\n')
any_failures = 1
示例2: cythonize_one
def cythonize_one(pyx_file, c_file, fingerprint, quiet, options=None):
from Cython.Compiler.Main import compile, default_options
from Cython.Compiler.Errors import CompileError, PyrexError
if fingerprint:
if not os.path.exists(options.cache):
try:
os.mkdir(options.cache)
except:
if not os.path.exists(options.cache):
raise
# Cython-generated c files are highly compressible.
# (E.g. a compression ratio of about 10 for Sage).
fingerprint_file = os.path.join(
options.cache, fingerprint + '-' + os.path.basename(c_file) + '.gz')
if os.path.exists(fingerprint_file):
if not quiet:
print("Found compiled %s in cache" % pyx_file)
os.utime(fingerprint_file, None)
open(c_file, 'wb').write(gzip.open(fingerprint_file).read())
return
if not quiet:
print("Cythonizing %s" % pyx_file)
if options is None:
options = CompilationOptions(default_options)
options.output_file = c_file
any_failures = 0
try:
result = compile([pyx_file], options)
if result.num_errors > 0:
any_failures = 1
except (EnvironmentError, PyrexError), e:
sys.stderr.write('%s\n' % e)
any_failures = 1
示例3: cythonize
def cythonize(source,
includes=(),
destdir_c=None,
destdir_h=None,
wdir=None):
from Cython.Compiler.Main import \
CompilationOptions, default_options, \
compile, \
PyrexError
from Cython.Compiler import Options
cwd = os.getcwd()
try:
name, ext = os.path.splitext(source)
outputs_c = [name+'.c']
outputs_h = [name+'.h', name+'_api.h']
# change working directory
if wdir:
os.chdir(wdir)
# run Cython on source
options = CompilationOptions(default_options)
options.output_file = outputs_c[0]
options.include_path = list(includes)
Options.generate_cleanup_code = 3
any_failures = 0
try:
result = compile(source, options)
if result.num_errors > 0:
any_failures = 1
except (EnvironmentError, PyrexError):
e = sys.exc_info()[1]
sys.stderr.write(str(e) + '\n')
any_failures = 1
if any_failures:
for output in outputs_c + outputs_h:
try:
os.remove(output)
except OSError:
pass
return 1
# move ouputs
for destdir, outputs in (
(destdir_c, outputs_c),
(destdir_h, outputs_h)):
if destdir is None: continue
for output in outputs:
dest = os.path.join(
destdir, os.path.basename(output))
try:
os.remove(dest)
except OSError:
pass
os.rename(output, dest)
#
return 0
#
finally:
os.chdir(cwd)
示例4: run_cython
def run_cython(cython_file, c_file):
assert have_cython
msg('Cythonizing %s -> %s', cython_file, c_file)
options = CythonCompilationOptions(cython_default_options)
options.output_file = c_file
try:
result = cython_compile([cython_file], options)
except (EnvironmentError, PyrexError), e:
error_msg(str(e))
示例5: test_func_transform
def test_func_transform(self):
options = CompilationOptions(default_options, ctypes=True)
context = options.create_context()
t = self.run_pipeline([NormalizeTree(self), ExternDefTransform(context)],
u"""\
cdef extern from "stdio.h":
int printf(char *, int *)\
""")
print self.codeToString(t)
self.assertEquals(self.codeToString(t),
"""\
with (cython.ctypes_extern)('stdio.h'):
printf = (cython.ctypes_func)('printf','c',ctypes.c_int,ctypes.POINTER(ctypes.c_char),ctypes.POINTER(ctypes.c_int))\
""")
示例6: cythonize_one
def cythonize_one(pyx_file, c_file, options=None):
from Cython.Compiler.Main import compile, default_options
from Cython.Compiler.Errors import CompileError, PyrexError
if options is None:
options = CompilationOptions(default_options)
options.output_file = c_file
any_failures = 0
try:
result = compile([pyx_file], options)
if result.num_errors > 0:
any_failures = 1
except (EnvironmentError, PyrexError), e:
sys.stderr.write(str(e) + '\n')
any_failures = 1
示例7: cythonize_one
def cythonize_one(pyx_file, c_file, fingerprint, quiet, options=None, raise_on_failure=True):
from Cython.Compiler.Main import compile, default_options
from Cython.Compiler.Errors import CompileError, PyrexError
if fingerprint:
if not os.path.exists(options.cache):
try:
os.mkdir(options.cache)
except:
if not os.path.exists(options.cache):
raise
# Cython-generated c files are highly compressible.
# (E.g. a compression ratio of about 10 for Sage).
fingerprint_file = join_path(
options.cache, "%s-%s%s" % (os.path.basename(c_file), fingerprint, gzip_ext))
if os.path.exists(fingerprint_file):
if not quiet:
print("Found compiled %s in cache" % pyx_file)
os.utime(fingerprint_file, None)
g = gzip_open(fingerprint_file, 'rb')
try:
f = open(c_file, 'wb')
try:
shutil.copyfileobj(g, f)
finally:
f.close()
finally:
g.close()
return
if not quiet:
print("Cythonizing %s" % pyx_file)
if options is None:
options = CompilationOptions(default_options)
options.output_file = c_file
any_failures = 0
try:
result = compile([pyx_file], options)
if result.num_errors > 0:
any_failures = 1
except (EnvironmentError, PyrexError), e:
sys.stderr.write('%s\n' % e)
any_failures = 1
# XXX
import traceback
traceback.print_exc()
示例8: run
def run(self):
"""Run - pass execution to generate_qcd"""
filepaths = generate_qcd(self.num_colours, self.precision,
self.representation)
from Cython.Build.Dependencies import cythonize_one
from Cython.Compiler.Main import CompilationOptions
options = CompilationOptions()
options.cplus = True
for src_path in filepaths:
if not src_path.endswith(".pyx"):
raise ValueError("Aborted attempt to cythonize file '{}'"
.format(src_path))
dest_path = src_path[-3:] + "cpp"
cythonize_one(src_path, dest_path, None, False, options=options)
示例9: extract
def extract(path, **kwargs):
name = os.path.splitext(os.path.relpath(path))[0].replace('/', '.')
options = CompilationOptions()
options.include_path.append('include')
options.language_level = 2
options.compiler_directives = dict(
c_string_type='str',
c_string_encoding='ascii',
)
context = options.create_context()
tree = parse_from_strings(name, open(path).read().decode('utf8'), context, **kwargs)
extractor = Visitor({'file': path})
extractor.visit(tree)
return extractor.events
示例10: cythonize
def cythonize():
try:
from Cython.Compiler.Main import CompilationOptions, default_options, \
compile, PyrexError
from Cython.Compiler import Options
import subprocess
for code in cythoncodes:
source = code[0] + '.pyx'
options = CompilationOptions(default_options)
options.output_file = code[0] + '.c'
options.include_path = code[1]
Options.generate_cleanup_code = 3
any_failures = False
try:
result = compile(source, options)
if result.num_errors > 0:
any_failures = True
if not any_failures:
callist = [cythcompiler,'-shared','-fwrapv','-Wall','-fno-strict-aliasing']
for x in CFLAGS:
callist.append(x)
for x in code[1]:
callist.append('-L' + x)
callist.append('-o')
callist.append('_' + code[0] + '.so')
callist.append(code[0] + '.c')
subprocess.call(callist)
except (EnvironmentError, PyrexError):
e = sys.exc_info()[1]
sys.stderr.write(str(e) + '\n')
any_failures = True
if any_failures:
try: os.remove(code[0] + '.c')
except OSError: pass
except:
raise ValueError
示例11: cythonize
def cythonize(module_list, exclude=[], nthreads=0, aliases=None, quiet=False, force=False,
exclude_failures=False, **options):
"""
Compile a set of source modules into C/C++ files and return a list of distutils
Extension objects for them.
As module list, pass either a glob pattern, a list of glob patterns or a list of
Extension objects. The latter allows you to configure the extensions separately
through the normal distutils options.
When using glob patterns, you can exclude certain module names explicitly
by passing them into the 'exclude' option.
For parallel compilation, set the 'nthreads' option to the number of
concurrent builds.
For a broad 'try to compile' mode that ignores compilation failures and
simply excludes the failed extensions, pass 'exclude_failures=True'. Note
that this only really makes sense for compiling .py files which can also
be used without compilation.
Additional compilation options can be passed as keyword arguments.
"""
if 'include_path' not in options:
options['include_path'] = ['.']
if 'common_utility_include_dir' in options:
if options.get('cache'):
raise NotImplementedError("common_utility_include_dir does not yet work with caching")
if not os.path.exists(options['common_utility_include_dir']):
os.makedirs(options['common_utility_include_dir'])
c_options = CompilationOptions(**options)
cpp_options = CompilationOptions(**options); cpp_options.cplus = True
ctx = c_options.create_context()
options = c_options
module_list = create_extension_list(
module_list,
exclude=exclude,
ctx=ctx,
quiet=quiet,
exclude_failures=exclude_failures,
aliases=aliases)
deps = create_dependency_tree(ctx, quiet=quiet)
build_dir = getattr(options, 'build_dir', None)
modules_by_cfile = {}
to_compile = []
for m in module_list:
if build_dir:
root = os.path.realpath(os.path.abspath(find_root_package_dir(m.sources[0])))
def copy_to_build_dir(filepath, root=root):
filepath_abs = os.path.realpath(os.path.abspath(filepath))
if os.path.isabs(filepath):
filepath = filepath_abs
if filepath_abs.startswith(root):
mod_dir = os.path.join(build_dir,
os.path.dirname(_relpath(filepath, root)))
if not os.path.isdir(mod_dir):
os.makedirs(mod_dir)
shutil.copy(filepath, mod_dir)
for dep in m.depends:
copy_to_build_dir(dep)
new_sources = []
for source in m.sources:
base, ext = os.path.splitext(source)
if ext in ('.pyx', '.py'):
if m.language == 'c++':
c_file = base + '.cpp'
options = cpp_options
else:
c_file = base + '.c'
options = c_options
# setup for out of place build directory if enabled
if build_dir:
c_file = os.path.join(build_dir, c_file)
dir = os.path.dirname(c_file)
if not os.path.isdir(dir):
os.makedirs(dir)
if os.path.exists(c_file):
c_timestamp = os.path.getmtime(c_file)
else:
c_timestamp = -1
# Priority goes first to modified files, second to direct
# dependents, and finally to indirect dependents.
if c_timestamp < deps.timestamp(source):
dep_timestamp, dep = deps.timestamp(source), source
priority = 0
else:
dep_timestamp, dep = deps.newest_dependency(source)
priority = 2 - (dep in deps.immediate_dependencies(source))
if force or c_timestamp < dep_timestamp:
if not quiet:
if source == dep:
print("Compiling %s because it changed." % source)
else:
print("Compiling %s because it depends on %s." % (source, dep))
if not force and hasattr(options, 'cache'):
#.........这里部分代码省略.........
示例12: parse_command_line
def parse_command_line(args):
from Cython.Compiler.Main import \
CompilationOptions, default_options
def pop_arg():
if args:
return args.pop(0)
else:
bad_usage()
def get_param(option):
tail = option[2:]
if tail:
return tail
else:
return pop_arg()
options = CompilationOptions(default_options)
sources = []
while args:
if args[0].startswith("-"):
option = pop_arg()
if option in ("-V", "--version"):
options.show_version = 1
elif option in ("-l", "--create-listing"):
options.use_listing_file = 1
elif option in ("-+", "--cplus"):
options.cplus = 1
elif option.startswith("--embed"):
ix = option.find('=')
if ix == -1:
Options.embed = "main"
else:
Options.embed = option[ix+1:]
elif option.startswith("-I"):
options.include_path.append(get_param(option))
elif option == "--include-dir":
options.include_path.append(pop_arg())
elif option in ("-w", "--working"):
options.working_path = pop_arg()
elif option in ("-o", "--output-file"):
options.output_file = pop_arg()
elif option in ("-r", "--recursive"):
options.recursive = 1
elif option in ("-t", "--timestamps"):
options.timestamps = 1
elif option in ("-f", "--force"):
options.timestamps = 0
elif option in ("-v", "--verbose"):
options.verbose += 1
elif option in ("-p", "--embed-positions"):
Options.embed_pos_in_docstring = 1
elif option in ("-z", "--pre-import"):
Options.pre_import = pop_arg()
elif option == "--cleanup":
Options.generate_cleanup_code = int(pop_arg())
elif option in ("-D", "--no-docstrings"):
Options.docstrings = False
elif option in ("-a", "--annotate"):
Options.annotate = True
elif option == "--convert-range":
Options.convert_range = True
elif option == "--line-directives":
options.emit_linenums = True
elif option == "--no-c-in-traceback":
options.c_line_in_traceback = False
elif option == "--gdb":
options.gdb_debug = True
options.output_dir = os.curdir
elif option == '-2':
options.language_level = 2
elif option == '-3':
options.language_level = 3
elif option == "--fast-fail":
Options.fast_fail = True
elif option in ('-Werror', '--warning-errors'):
Options.warning_errors = True
elif option == "--disable-function-redefinition":
Options.disable_function_redefinition = True
elif option == "--directive" or option.startswith('-X'):
if option.startswith('-X') and option[2:].strip():
x_args = option[2:]
else:
x_args = pop_arg()
try:
options.compiler_directives = Options.parse_directive_list(
x_args, relaxed_bool=True,
current_settings=options.compiler_directives)
except ValueError, e:
sys.stderr.write("Error in compiler directive: %s\n" % e.args[0])
sys.exit(1)
elif option.startswith('--debug'):
option = option[2:].replace('-', '_')
import DebugFlags
if option in dir(DebugFlags):
setattr(DebugFlags, option, True)
else:
sys.stderr.write("Unknown debug flag: %s\n" % option)
bad_usage()
#.........这里部分代码省略.........
示例13: parse_command_line
def parse_command_line(args):
from Cython.Compiler.Main import \
CompilationOptions, default_options
def pop_arg():
if args:
return args.pop(0)
else:
bad_usage()
def get_param(option):
tail = option[2:]
if tail:
return tail
else:
return pop_arg()
options = CompilationOptions(default_options)
sources = []
while args:
if args[0].startswith("-"):
option = pop_arg()
if option in ("-V", "--version"):
options.show_version = 1
elif option in ("-l", "--create-listing"):
options.use_listing_file = 1
elif option in ("-C", "--compile"):
options.c_only = 0
elif option in ("-X", "--link"):
options.c_only = 0
options.obj_only = 0
elif option in ("-+", "--cplus"):
options.cplus = 1
elif option.startswith("-I"):
options.include_path.append(get_param(option))
elif option == "--include-dir":
options.include_path.append(pop_arg())
elif option in ("-w", "--working"):
options.working_path = pop_arg()
elif option in ("-o", "--output-file"):
options.output_file = pop_arg()
elif option in ("-r", "--recursive"):
options.recursive = 1
elif option in ("-t", "--timestamps"):
options.timestamps = 1
elif option in ("-f", "--force"):
options.timestamps = 0
elif option in ("-v", "--verbose"):
options.verbose += 1
elif option in ("-p", "--embed-positions"):
Options.embed_pos_in_docstring = 1
elif option in ("-z", "--pre-import"):
Options.pre_import = pop_arg()
elif option == "--incref-local-binop":
Options.incref_local_binop = 1
elif option == "--cleanup":
Options.generate_cleanup_code = int(pop_arg())
elif option in ("-D", "--no-docstrings"):
Options.docstrings = False
elif option in ("-a", "--annotate"):
Options.annotate = True
elif option == "--convert-range":
Options.convert_range = True
elif option == "--line-directives":
options.emit_linenums = True
elif option in ("-X", "--directive"):
try:
options.pragma_overrides = Options.parse_option_list(pop_arg())
except ValueError, e:
sys.stderr.write("Error in compiler directive: %s\n" % e.message)
sys.exit(1)
else:
bad_usage()
else:
arg = pop_arg()
if arg.endswith(".pyx"):
sources.append(arg)
elif arg.endswith(".py"):
# maybe do some other stuff, but this should work for now
sources.append(arg)
elif arg.endswith(".o"):
options.objects.append(arg)
else:
sys.stderr.write(
"cython: %s: Unknown filename suffix\n" % arg)
示例14: cythonize
def cythonize(module_list, exclude=[], nthreads=0, aliases=None, quiet=False, **options):
if 'include_path' not in options:
options['include_path'] = ['.']
c_options = CompilationOptions(**options)
cpp_options = CompilationOptions(**options); cpp_options.cplus = True
ctx = c_options.create_context()
module_list = create_extension_list(
module_list,
exclude=exclude,
ctx=ctx,
aliases=aliases)
deps = create_dependency_tree(ctx)
to_compile = []
for m in module_list:
new_sources = []
for source in m.sources:
base, ext = os.path.splitext(source)
if ext in ('.pyx', '.py'):
if m.language == 'c++':
c_file = base + '.cpp'
options = cpp_options
else:
c_file = base + '.c'
options = c_options
if os.path.exists(c_file):
c_timestamp = os.path.getmtime(c_file)
else:
c_timestamp = -1
# Priority goes first to modified files, second to direct
# dependents, and finally to indirect dependents.
if c_timestamp < deps.timestamp(source):
dep_timestamp, dep = deps.timestamp(source), source
priority = 0
else:
dep_timestamp, dep = deps.newest_dependency(source)
priority = 2 - (dep in deps.immediate_dependencies(source))
if c_timestamp < dep_timestamp:
if not quiet:
if source == dep:
print("Compiling %s because it changed." % source)
else:
print("Compiling %s because it depends on %s." % (source, dep))
to_compile.append((priority, source, c_file, options))
new_sources.append(c_file)
else:
new_sources.append(source)
m.sources = new_sources
to_compile.sort()
if nthreads:
# Requires multiprocessing (or Python >= 2.6)
try:
import multiprocessing
pool = multiprocessing.Pool(nthreads)
pool.map(cythonize_one_helper, to_compile)
except ImportError:
print("multiprocessing required for parallel cythonization")
nthreads = 0
if not nthreads:
for priority, pyx_file, c_file, options in to_compile:
cythonize_one(pyx_file, c_file, options)
return module_list
示例15: cythonize
def cythonize(module_list, exclude=[], nthreads=0, aliases=None, quiet=False, force=False,
exclude_failures=False, **options):
"""
Compile a set of source modules into C/C++ files and return a list of distutils
Extension objects for them.
As module list, pass either a glob pattern, a list of glob patterns or a list of
Extension objects. The latter allows you to configure the extensions separately
through the normal distutils options.
When using glob patterns, you can exclude certain module names explicitly
by passing them into the 'exclude' option.
For parallel compilation, set the 'nthreads' option to the number of
concurrent builds.
For a broad 'try to compile' mode that ignores compilation failures and
simply excludes the failed extensions, pass 'exclude_failures=True'. Note
that this only really makes sense for compiling .py files which can also
be used without compilation.
Additional compilation options can be passed as keyword arguments.
"""
if 'include_path' not in options:
options['include_path'] = ['.']
c_options = CompilationOptions(**options)
cpp_options = CompilationOptions(**options); cpp_options.cplus = True
ctx = c_options.create_context()
module_list = create_extension_list(
module_list,
exclude=exclude,
ctx=ctx,
quiet=quiet,
exclude_failures=exclude_failures,
aliases=aliases)
deps = create_dependency_tree(ctx, quiet=quiet)
modules_by_cfile = {}
to_compile = []
for m in module_list:
new_sources = []
for source in m.sources:
base, ext = os.path.splitext(source)
if ext in ('.pyx', '.py'):
if m.language == 'c++':
c_file = base + '.cpp'
options = cpp_options
else:
c_file = base + '.c'
options = c_options
if os.path.exists(c_file):
c_timestamp = os.path.getmtime(c_file)
else:
c_timestamp = -1
# Priority goes first to modified files, second to direct
# dependents, and finally to indirect dependents.
if c_timestamp < deps.timestamp(source):
dep_timestamp, dep = deps.timestamp(source), source
priority = 0
else:
dep_timestamp, dep = deps.newest_dependency(source)
priority = 2 - (dep in deps.immediate_dependencies(source))
if force or c_timestamp < dep_timestamp:
if not quiet:
if source == dep:
print("Compiling %s because it changed." % source)
else:
print("Compiling %s because it depends on %s." % (source, dep))
if not force and hasattr(options, 'cache'):
extra = m.language
fingerprint = deps.transitive_fingerprint(source, extra)
else:
fingerprint = None
to_compile.append((priority, source, c_file, fingerprint, quiet,
options, not exclude_failures))
new_sources.append(c_file)
if c_file not in modules_by_cfile:
modules_by_cfile[c_file] = [m]
else:
modules_by_cfile[c_file].append(m)
else:
new_sources.append(source)
m.sources = new_sources
if hasattr(options, 'cache'):
if not os.path.exists(options.cache):
os.mkdir(options.cache)
to_compile.sort()
if nthreads:
# Requires multiprocessing (or Python >= 2.6)
try:
import multiprocessing
pool = multiprocessing.Pool(nthreads)
pool.map(cythonize_one_helper, to_compile)
except ImportError:
print("multiprocessing required for parallel cythonization")
nthreads = 0
if not nthreads:
for args in to_compile:
cythonize_one(*args[1:])
if exclude_failures:
#.........这里部分代码省略.........