def test_record_extensions(self): install_dir = self.mkdtemp() project_dir, dist = self.create_dist(ext_modules=[ Extension('xx', ['xxmodule.c'])]) self.addCleanup(os.chdir, os.getcwd()) os.chdir(project_dir) support.copy_xxmodule_c(project_dir) buildextcmd = build_ext(dist) support.fixup_build_ext(buildextcmd) buildextcmd.ensure_finalized() cmd = install(dist) dist.command_obj['install'] = cmd dist.command_obj['build_ext'] = buildextcmd cmd.root = install_dir cmd.record = os.path.join(project_dir, 'RECORD') cmd.ensure_finalized() cmd.run() f = open(cmd.record) try: content = f.read() finally: f.close() found = [os.path.basename(line) for line in content.splitlines()] expected = [_make_ext_name('xx'), 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] self.assertEqual(found, expected)
def test_record_extensions(self): cmd = test_support.missing_compiler_executable() if cmd is not None: self.skipTest('The %r command is not found' % cmd) install_dir = self.mkdtemp() project_dir, dist = self.create_dist(ext_modules=[ Extension('xx', ['xxmodule.c'])]) os.chdir(project_dir) support.copy_xxmodule_c(project_dir) buildextcmd = build_ext(dist) support.fixup_build_ext(buildextcmd) buildextcmd.ensure_finalized() cmd = install(dist) dist.command_obj['install'] = cmd dist.command_obj['build_ext'] = buildextcmd cmd.root = install_dir cmd.record = os.path.join(project_dir, 'filelist') cmd.ensure_finalized() cmd.run() f = open(cmd.record) try: content = f.read() finally: f.close() found = [os.path.basename(line) for line in content.splitlines()] expected = [_make_ext_name('xx'), 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] self.assertEqual(found, expected)
def test_record_extensions(self): install_dir = self.mkdtemp() project_dir, dist = self.create_dist(ext_modules=[Extension("xx", ["xxmodule.c"])]) os.chdir(project_dir) support.copy_xxmodule_c(project_dir) buildextcmd = build_ext(dist) support.fixup_build_ext(buildextcmd) buildextcmd.ensure_finalized() cmd = install(dist) dist.command_obj["install"] = cmd dist.command_obj["build_ext"] = buildextcmd cmd.root = install_dir cmd.record = os.path.join(project_dir, "filelist") cmd.ensure_finalized() cmd.run() f = open(cmd.record) try: content = f.read() finally: f.close() found = [os.path.basename(line) for line in content.splitlines()] expected = [_make_ext_name("xx"), "UNKNOWN-0.0.0-py%s.%s.egg-info" % sys.version_info[:2]] self.assertEqual(found, expected)
def test_record_extensions(self): install_dir = self.mkdtemp() project_dir, dist = self.create_dist( ext_modules=[Extension('xx', ['xxmodule.c'])]) os.chdir(project_dir) support.copy_xxmodule_c(project_dir) buildextcmd = build_ext(dist) support.fixup_build_ext(buildextcmd) buildextcmd.ensure_finalized() cmd = install(dist) dist.command_obj['install'] = cmd dist.command_obj['build_ext'] = buildextcmd cmd.root = install_dir cmd.record = os.path.join(project_dir, 'filelist') cmd.ensure_finalized() cmd.run() f = open(cmd.record) try: content = f.read() finally: f.close() found = [os.path.basename(line) for line in content.splitlines()] expected = [ _make_ext_name('xx'), 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2] ] self.assertEqual(found, expected)
def test_build_ext(self): cmd = support.missing_compiler_executable() if cmd is not None: self.skipTest('The %r command is not found' % cmd) global ALREADY_TESTED copy_xxmodule_c(self.tmp_dir) xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: self.skipTest('Already tested in %s' % ALREADY_TESTED) else: ALREADY_TESTED = type(self).__name__ code = textwrap.dedent(""" tmp_dir = {self.tmp_dir!r} import sys import unittest from test import support sys.path.insert(0, tmp_dir) import xx class Tests(unittest.TestCase): def test_xx(self): for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13,15), 28) self.assertEqual(xx.new().demo(), None) if support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertIsInstance(xx.Null(), xx.Null) self.assertIsInstance(xx.Str(), xx.Str) unittest.main() """.format(**locals())) assert_python_ok('-c', code)
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void initfoo(void) {};\n') ext = Extension('foo', [c_file]) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) self.assertEqual( os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.compiler = None cmd.inplace = 0 cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertEqual( os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar') return
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void initfoo(void) {};\n') ext = Extension('foo', [c_file]) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) self.assertEqual(os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.compiler = None cmd.inplace = 0 cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertEqual(os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar') return
def test_get_outputs(self): cmd = support.missing_compiler_executable() if cmd is not None: self.skipTest('The %r command is not found' % cmd) tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void PyInit_foo(void) {}\n') ext = Extension('foo', [c_file], optional=False) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') self.assertTrue(so_file.endswith(ext_suffix)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.inplace = 0 cmd.compiler = None cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertTrue(so_file.endswith(ext_suffix)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar')
def test_build_ext(self): global ALREADY_TESTED support.copy_xxmodule_c(self.tmp_dir) self.xx_created = True xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not test_support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() #Broken after issue 7712(r78136) : add a temp_cwd context manager to test_support ... #Without current working dir: "...cannot find -lpython27" #NOTE: [py3k svn r85559] First (uncontroversial) part of issue 9807, barry.warsaw, 2010-10-16 : # new _fixup_command is bogus, so we will use own work-around cmd.library_dirs.insert(0, test_support.SAVEDCWD) cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: return else: ALREADY_TESTED = True import xx for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13,15), 28) self.assertEqual(xx.new().demo(), None) if test_support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertTrue(isinstance(xx.Null(), xx.Null)) self.assertTrue(isinstance(xx.Str(), xx.Str))
def test_build_ext(self): global ALREADY_TESTED support.copy_xxmodule_c(self.tmp_dir) self.xx_created = True xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not test_support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() #Broken after issue 7712(r78136) : add a temp_cwd context manager to test_support ... #Without current working dir: "...cannot find -lpython27" #NOTE: [py3k svn r85559] First (uncontroversial) part of issue 9807, barry.warsaw, 2010-10-16 : # new _fixup_command is bogus, so we will use own work-around cmd.library_dirs.insert(0, test_support.SAVEDCWD) cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: return else: ALREADY_TESTED = True import xx for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13, 15), 28) self.assertEqual(xx.new().demo(), None) if test_support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertTrue(isinstance(xx.Null(), xx.Null)) self.assertTrue(isinstance(xx.Str(), xx.Str))
def test_build_ext(self): cmd = support.missing_compiler_executable() if cmd is not None: self.skipTest('The %r command is not found' % cmd) global ALREADY_TESTED copy_xxmodule_c(self.tmp_dir) xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: self.skipTest('Already tested in %s' % ALREADY_TESTED) else: ALREADY_TESTED = type(self).__name__ import xx for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13,15), 28) self.assertEqual(xx.new().demo(), None) if support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertIsInstance(xx.Null(), xx.Null) self.assertIsInstance(xx.Str(), xx.Str)
def test_build_ext(self): global ALREADY_TESTED support.copy_xxmodule_c(self.tmp_dir) self.xx_created = True xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not test_support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: return else: ALREADY_TESTED = True import xx for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13,15), 28) self.assertEqual(xx.new().demo(), None) if test_support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertTrue(isinstance(xx.Null(), xx.Null)) self.assertTrue(isinstance(xx.Str(), xx.Str))
def test_build_ext(self): global ALREADY_TESTED support.copy_xxmodule_c(self.tmp_dir) self.xx_created = True xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not test_support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: self.skipTest('Already tested in %s' % ALREADY_TESTED) else: ALREADY_TESTED = type(self).__name__ import xx for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13, 15), 28) self.assertEqual(xx.new().demo(), None) if test_support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertIsInstance(xx.Null(), xx.Null) self.assertIsInstance(xx.Str(), xx.Str)
def test_build_ext(self): global ALREADY_TESTED copy_xxmodule_c(self.tmp_dir) xx_c = os.path.join(self.tmp_dir, "xxmodule.c") xx_ext = Extension("xx", [xx_c]) dist = Distribution({"name": "xx", "ext_modules": [xx_ext]}) dist.package_dir = self.tmp_dir cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: self.skipTest("Already tested in %s" % ALREADY_TESTED) else: ALREADY_TESTED = type(self).__name__ import xx for attr in ("error", "foo", "new", "roj"): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13, 15), 28) self.assertEqual(xx.new().demo(), None) if support.HAVE_DOCSTRINGS: doc = "This is a template module just for instruction." self.assertEqual(xx.__doc__, doc) self.assertIsInstance(xx.Null(), xx.Null) self.assertIsInstance(xx.Str(), xx.Str)
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void PyInit_foo(void) {}\n') ext = Extension('foo', [c_file], optional=False) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = build_ext(dist) fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') # issue #5977 : distutils build_ext.get_outputs # returns wrong result with --inplace other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) so_ext = sysconfig.get_config_var('SO') self.assertTrue(so_file.endswith(so_ext)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.inplace = 0 cmd.compiler = None cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertTrue(so_file.endswith(so_ext)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) # inplace = 0, cmd.package = 'bar' build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') # checking that the last directory is the build_dir path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) # inplace = 1, cmd.package = 'bar' cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar')
def compile_c_extension( generated_source_path: str, build_dir: Optional[str] = None, verbose: bool = False, keep_asserts: bool = True, ) -> str: """Compile the generated source for a parser generator into an extension module. The extension module will be generated in the same directory as the provided path for the generated source, with the same basename (in addition to extension module metadata). For example, for the source mydir/parser.c the generated extension in a darwin system with python 3.8 will be mydir/parser.cpython-38-darwin.so. If *build_dir* is provided, that path will be used as the temporary build directory of distutils (this is useful in case you want to use a temporary directory). """ import distutils.log from distutils.core import Distribution, Extension from distutils.command.clean import clean # type: ignore from distutils.command.build_ext import build_ext # type: ignore from distutils.tests.support import fixup_build_ext # type: ignore if verbose: distutils.log.set_verbosity(distutils.log.DEBUG) source_file_path = pathlib.Path(generated_source_path) extension_name = source_file_path.stem extra_compile_args = get_extra_flags("CFLAGS", "PY_CFLAGS_NODIST") extra_compile_args.append("-DPy_BUILD_CORE_MODULE") # Define _Py_TEST_PEGEN to not call PyAST_Validate() in Parser/pegen.c extra_compile_args.append("-D_Py_TEST_PEGEN") extra_link_args = get_extra_flags("LDFLAGS", "PY_LDFLAGS_NODIST") if keep_asserts: extra_compile_args.append("-UNDEBUG") extension = [ Extension( extension_name, sources=[ str(MOD_DIR.parent.parent.parent / "Python" / "Python-ast.c"), str(MOD_DIR.parent.parent.parent / "Python" / "asdl.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "tokenizer.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "pegen.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "string_parser.c"), str(MOD_DIR.parent / "peg_extension" / "peg_extension.c"), generated_source_path, ], include_dirs=[ str(MOD_DIR.parent.parent.parent / "Include" / "internal"), str(MOD_DIR.parent.parent.parent / "Parser"), ], extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, ) ] dist = Distribution({"name": extension_name, "ext_modules": extension}) cmd = build_ext(dist) fixup_build_ext(cmd) cmd.inplace = True if build_dir: cmd.build_temp = build_dir cmd.build_lib = build_dir cmd.ensure_finalized() cmd.run() extension_path = source_file_path.parent / cmd.get_ext_filename(extension_name) shutil.move(cmd.get_ext_fullpath(extension_name), extension_path) cmd = clean(dist) cmd.finalize_options() cmd.run() return extension_path
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void initfoo(void) {};\n') ext = Extension('foo', [c_file]) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') # issue #5977 : distutils build_ext.get_outputs # returns wrong result with --inplace other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() #Without current working dir: "...cannot find -lpython27" #NOTE: After issue #7712(r78136) test cannot use old_wd ! #cmd.library_dirs.insert(0, old_wd) #NOTE: [py3k svn r85559] First (uncontroversial) part of issue 9807, barry.warsaw, 2010-10-16 : # new _fixup_command is bogus, so we will use own work-around cmd.library_dirs.insert(0, test_support.SAVEDCWD) os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) self.assertEqual( os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.compiler = None cmd.inplace = 0 cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertEqual( os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) # inplace = 0, cmd.package = 'bar' build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') # checking that the last directory is the build_dir path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) # inplace = 1, cmd.package = 'bar' cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar')
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void PyInit_foo(void) {}\n') ext = Extension('foo', [c_file], optional=False) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = build_ext(dist) fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') # issue #5977 : distutils build_ext.get_outputs # returns wrong result with --inplace other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') self.assertTrue(so_file.endswith(ext_suffix)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.inplace = 0 cmd.compiler = None cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertTrue(so_file.endswith(ext_suffix)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) # inplace = 0, cmd.package = 'bar' build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') # checking that the last directory is the build_dir path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) # inplace = 1, cmd.package = 'bar' cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar')
def compile_c_extension( generated_source_path: str, build_dir: Optional[str] = None, verbose: bool = False, keep_asserts: bool = True, ) -> str: """Compile the generated source for a parser generator into an extension module. The extension module will be generated in the same directory as the provided path for the generated source, with the same basename (in addition to extension module metadata). For example, for the source mydir/parser.c the generated extension in a darwin system with python 3.8 will be mydir/parser.cpython-38-darwin.so. If *build_dir* is provided, that path will be used as the temporary build directory of distutils (this is useful in case you want to use a temporary directory). """ if verbose: distutils.log.set_verbosity(distutils.log.DEBUG) source_file_path = pathlib.Path(generated_source_path) extension_name = source_file_path.stem extra_compile_args = [] if not sys.platform.startswith('win'): extra_compile_args.append("-std=c99") if keep_asserts: extra_compile_args.append("-UNDEBUG") extension = [ Extension( extension_name, sources=[ str(MOD_DIR.parent.parent.parent / "Python" / "Python-ast.c"), str(MOD_DIR.parent.parent.parent / "Python" / "asdl.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "tokenizer.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "pegen" / "pegen.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "pegen" / "parse_string.c"), str(MOD_DIR.parent / "peg_extension" / "peg_extension.c"), generated_source_path, ], include_dirs=[ str(MOD_DIR.parent.parent.parent / "Include" / "internal"), str(MOD_DIR.parent.parent.parent / "Parser"), str(MOD_DIR.parent.parent.parent / "Parser" / "pegen"), ], extra_compile_args=extra_compile_args, ) ] dist = Distribution({"name": extension_name, "ext_modules": extension}) cmd = build_ext(dist) fixup_build_ext(cmd) cmd.inplace = True if build_dir: cmd.build_temp = build_dir cmd.ensure_finalized() cmd.run() extension_path = source_file_path.parent / cmd.get_ext_filename(extension_name) shutil.move(cmd.get_ext_fullpath(extension_name), extension_path) cmd = clean(dist) cmd.finalize_options() cmd.run() return extension_path
def compile_c_extension( generated_source_path: str, build_dir: Optional[str] = None, verbose: bool = False, keep_asserts: bool = True, disable_optimization: bool = False, library_dir: Optional[str] = None, ) -> str: """Compile the generated source for a parser generator into an extension module. The extension module will be generated in the same directory as the provided path for the generated source, with the same basename (in addition to extension module metadata). For example, for the source mydir/parser.c the generated extension in a darwin system with python 3.8 will be mydir/parser.cpython-38-darwin.so. If *build_dir* is provided, that path will be used as the temporary build directory of distutils (this is useful in case you want to use a temporary directory). If *library_dir* is provided, that path will be used as the directory for a static library of the common parser sources (this is useful in case you are creating multiple extensions). """ import distutils.log from distutils.core import Distribution, Extension from distutils.tests.support import fixup_build_ext # type: ignore from distutils.ccompiler import new_compiler from distutils.dep_util import newer_group from distutils.sysconfig import customize_compiler if verbose: distutils.log.set_threshold(distutils.log.DEBUG) source_file_path = pathlib.Path(generated_source_path) extension_name = source_file_path.stem extra_compile_args = get_extra_flags("CFLAGS", "PY_CFLAGS_NODIST") extra_compile_args.append("-DPy_BUILD_CORE_MODULE") # Define _Py_TEST_PEGEN to not call PyAST_Validate() in Parser/pegen.c extra_compile_args.append("-D_Py_TEST_PEGEN") extra_link_args = get_extra_flags("LDFLAGS", "PY_LDFLAGS_NODIST") if keep_asserts: extra_compile_args.append("-UNDEBUG") if disable_optimization: if sys.platform == 'win32': extra_compile_args.append("/Od") extra_link_args.append("/LTCG:OFF") else: extra_compile_args.append("-O0") if sysconfig.get_config_var("GNULD") == "yes": extra_link_args.append("-fno-lto") common_sources = [ str(MOD_DIR.parent.parent.parent / "Python" / "Python-ast.c"), str(MOD_DIR.parent.parent.parent / "Python" / "asdl.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "tokenizer.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "pegen.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "pegen_errors.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "action_helpers.c"), str(MOD_DIR.parent.parent.parent / "Parser" / "string_parser.c"), str(MOD_DIR.parent / "peg_extension" / "peg_extension.c"), ] include_dirs = [ str(MOD_DIR.parent.parent.parent / "Include" / "internal"), str(MOD_DIR.parent.parent.parent / "Parser"), ] extension = Extension( extension_name, sources=[generated_source_path], extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, ) dist = Distribution({"name": extension_name, "ext_modules": [extension]}) cmd = dist.get_command_obj("build_ext") fixup_build_ext(cmd) cmd.build_lib = str(source_file_path.parent) cmd.include_dirs = include_dirs if build_dir: cmd.build_temp = build_dir cmd.ensure_finalized() compiler = new_compiler() customize_compiler(compiler) compiler.set_include_dirs(cmd.include_dirs) compiler.set_library_dirs(cmd.library_dirs) # build static lib if library_dir: library_filename = compiler.library_filename(extension_name, output_dir=library_dir) if newer_group(common_sources, library_filename, 'newer'): if sys.platform == 'win32': pdb = compiler.static_lib_format % (extension_name, '.pdb') compile_opts = [f"/Fd{library_dir}\\{pdb}"] compile_opts.extend(extra_compile_args) else: compile_opts = extra_compile_args objects = compiler.compile(common_sources, output_dir=library_dir, debug=cmd.debug, extra_postargs=compile_opts) compiler.create_static_lib(objects, extension_name, output_dir=library_dir, debug=cmd.debug) if sys.platform == 'win32': compiler.add_library_dir(library_dir) extension.libraries = [extension_name] elif sys.platform == 'darwin': compiler.set_link_objects([ '-Wl,-force_load', library_filename, ]) else: compiler.set_link_objects([ '-Wl,--whole-archive', library_filename, '-Wl,--no-whole-archive', ]) else: extension.sources[0:0] = common_sources # Compile the source code to object files. ext_path = cmd.get_ext_fullpath(extension_name) if newer_group(extension.sources, ext_path, 'newer'): objects = compiler.compile(extension.sources, output_dir=cmd.build_temp, debug=cmd.debug, extra_postargs=extra_compile_args) else: objects = compiler.object_filenames(extension.sources, output_dir=cmd.build_temp) # Now link the object files together into a "shared object" compiler.link_shared_object( objects, ext_path, libraries=cmd.get_libraries(extension), extra_postargs=extra_link_args, export_symbols=cmd.get_export_symbols(extension), debug=cmd.debug, build_temp=cmd.build_temp) return pathlib.Path(ext_path)
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void initfoo(void) {};\n') ext = Extension('foo', [c_file]) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') # issue #5977 : distutils build_ext.get_outputs # returns wrong result with --inplace other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() #Without current working dir: "...cannot find -lpython27" #NOTE: After issue #7712(r78136) test cannot use old_wd ! #cmd.library_dirs.insert(0, old_wd) #NOTE: [py3k svn r85559] First (uncontroversial) part of issue 9807, barry.warsaw, 2010-10-16 : # new _fixup_command is bogus, so we will use own work-around cmd.library_dirs.insert(0, test_support.SAVEDCWD) os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) self.assertEqual(os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.compiler = None cmd.inplace = 0 cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertEqual(os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) # inplace = 0, cmd.package = 'bar' build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') # checking that the last directory is the build_dir path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) # inplace = 1, cmd.package = 'bar' cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, 'bar')
def test_get_outputs(self): tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, "foo.c") self.write_file(c_file, "void PyInit_foo(void) {}\n") ext = Extension("foo", [c_file], optional=False) dist = Distribution({"name": "xx", "ext_modules": [ext]}) cmd = build_ext(dist) fixup_build_ext(cmd) cmd.ensure_finalized() self.assertEqual(len(cmd.get_outputs()), 1) cmd.build_lib = os.path.join(self.tmp_dir, "build") cmd.build_temp = os.path.join(self.tmp_dir, "tempt") # issue #5977 : distutils build_ext.get_outputs # returns wrong result with --inplace other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = 1 cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) self.assertTrue(os.path.exists(so_file)) so_ext = sysconfig.get_config_var("SO") self.assertTrue(so_file.endswith(so_ext)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, other_tmp_dir) cmd.inplace = 0 cmd.compiler = None cmd.run() so_file = cmd.get_outputs()[0] self.assertTrue(os.path.exists(so_file)) self.assertTrue(so_file.endswith(so_ext)) so_dir = os.path.dirname(so_file) self.assertEqual(so_dir, cmd.build_lib) # inplace = 0, cmd.package = 'bar' build_py = cmd.get_finalized_command("build_py") build_py.package_dir = {"": "bar"} path = cmd.get_ext_fullpath("foo") # checking that the last directory is the build_dir path = os.path.split(path)[0] self.assertEqual(path, cmd.build_lib) # inplace = 1, cmd.package = 'bar' cmd.inplace = 1 other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath("foo") finally: os.chdir(old_wd) # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] self.assertEqual(lastdir, "bar")