我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用distutils.core.setup.py()。
def test_run_setup_uses_current_dir(self): # This tests that the setup script is run with the current directory # as its own current directory; this was temporarily broken by a # previous patch when TESTFN did not use the current directory. sys.stdout = StringIO.StringIO() cwd = os.getcwd() # Create a directory and write the setup.py file there: os.mkdir(test.test_support.TESTFN) setup_py = os.path.join(test.test_support.TESTFN, "setup.py") distutils.core.run_setup( self.write_setup(setup_prints_cwd, path=setup_py)) output = sys.stdout.getvalue() if output.endswith("\n"): output = output[:-1] self.assertEqual(cwd, output)
def test_debug_mode(self): # this covers the code called when DEBUG is set sys.argv = ['setup.py', '--name'] with captured_stdout() as stdout: distutils.core.setup(name='bar') stdout.seek(0) self.assertEqual(stdout.read(), 'bar\n') distutils.core.DEBUG = True try: with captured_stdout() as stdout: distutils.core.setup(name='bar') finally: distutils.core.DEBUG = False stdout.seek(0) wanted = "options (after parsing config files):\n" self.assertEqual(stdout.readlines()[0], wanted)
def get_version_info(): # Adding the git rev number needs to be done inside # write_version_py(), otherwise the import of pyfunt.version messes # up the build under Python 3. FULLVERSION = VERSION if os.path.exists('.git'): GIT_REVISION = git_version() elif os.path.exists('pyfunt/version.py'): # must be a source distribution, use existing version file # load it as a separate module to not load pyfunt/__init__.py import imp version = imp.load_source('pyfunt.version', 'pyfunt/version.py') GIT_REVISION = version.git_revision else: GIT_REVISION = "Unknown" if not ISRELEASED: FULLVERSION += '.dev0+' + GIT_REVISION[:7] return FULLVERSION, GIT_REVISION
def write_version_py(filename='pyfunt/version.py'): cnt = """\ # THIS FILE IS GENERATED FROM PYFUNT SETUP.PY\ short_version = '%(version)s'\ version = '%(version)s'\ full_version = '%(full_version)s'\ git_revision = '%(git_revision)s'\ release = %(isrelease)s\ if not release:\ version = full_version\ """ FULLVERSION, GIT_REVISION = get_version_info() a = open(filename, 'w') try: a.write(cnt % {'version': VERSION, 'full_version': FULLVERSION, 'git_revision': GIT_REVISION, 'isrelease': str(ISRELEASED)}) finally: a.close()
def rewrite(self, version=None): if not version: version = self.current with open(join(here, 'mimesis', '__version__.py'), 'r+') as f: version_str = '__version__ = \'{}\''.format(version) regexp = r'__version__ = .*' meta = re.sub(regexp, version_str, f.read()) f.seek(0) f.write(meta) f.truncate() print('Updated! Current version is: ' '\033[34m{}\033[0m.\n'.format(version)) exit()
def _generate_code(self, routine, helpers): with open('%s.py' % self.module_name, 'w') as f: printed = ", ".join( [str(res.expr) for res in routine.result_variables]) # convert OutputArguments to return value like f2py args = filter(lambda x: not isinstance( x, OutputArgument), routine.arguments) retvals = [] for val in routine.result_variables: if isinstance(val, Result): retvals.append('nameless') else: retvals.append(val.result_var) print(DummyWrapper.template % { 'name': routine.name, 'expr': printed, 'args': ", ".join([str(a.name) for a in args]), 'retvals': ", ".join([str(val) for val in retvals]) }, end="", file=f)
def run(self): import os try: import pyflakes.scripts.pyflakes as flakes except ImportError: print("In order to run the audit, you need to have PyFlakes installed.") sys.exit(-1) # We don't want to audit external dependencies ext = ('mpmath',) dirs = (os.path.join(*d) for d in (m.split('.') for m in modules) if d[1] not in ext) warns = 0 for dir in dirs: for filename in os.listdir(dir): if filename.endswith('.py') and filename != '__init__.py': warns += flakes.checkPath(os.path.join(dir, filename)) if warns > 0: print("Audit finished with total %d warnings" % warns)
def _obtain_version(): # if we're running on a git checkout we generate # version.py and if we're running from a source dist # we use the existing version.py if os.path.isdir(os.path.join(ROOT, ".git")): tag = os.environ.get("GIT_DESCRIBE_TAG", None) if tag is None or tag == "": out = subprocess.check_output(['git', 'describe', '--tags']) tag = out.decode('utf-8').strip() if tag == '': raise Exception("git describe didn't give us a tag") if tag is None: raise Exception("Could not obtain git tag") # the tag may be only "v2.1" or may be "v2.1-NN-ABCEFG", # if the latter we drop the extra stuff pieces = tag.replace("v", "").split("-") version = pieces[0] print("git tag is %s, version is %s" % (tag, version)) return version elif os.path.isfile(VERSION_PY): from conda_kapsel.version import version return version else: raise Exception("Not a git checkout and no file %s" % VERSION_PY)
def git_version(): # Return the git revision as a string # copied from numpy setup.py def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen( cmd, stdout=subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = 'Unknown' return GIT_REVISION
def test_run_setup_uses_current_dir(self): # This tests that the setup script is run with the current directory # as its own current directory; this was temporarily broken by a # previous patch when TESTFN did not use the current directory. sys.stdout = io.StringIO() cwd = os.getcwd() # Create a directory and write the setup.py file there: os.mkdir(test.support.TESTFN) setup_py = os.path.join(test.support.TESTFN, "setup.py") distutils.core.run_setup( self.write_setup(setup_prints_cwd, path=setup_py)) output = sys.stdout.getvalue() if output.endswith("\n"): output = output[:-1] self.assertEqual(cwd, output)
def execute_makefile_commands(commands, alias, verbose=False): cmds = commands[alias] for cmd in cmds: # Parse string in a shell-like fashion # (incl quoted strings and comments) parsed_cmd = shlex.split(cmd, comments=True) # Execute command if not empty (ie, not just a comment) if parsed_cmd: if verbose: print("Running command: " + cmd) # Launch the command and wait to finish (synchronized call) subprocess.check_call(parsed_cmd) # # Main setup.py config # # # Executing makefile commands if specified
def main () : if platform.architecture()[0] == "32bit": helper = 'helper32' else : helper = 'helper64' py2exe_options = dict( packages = [], optimize=2, compressed=True, # uncompressed may or may not have a faster startup bundle_files=3, dist_dir=helper, ) setup(console=['eml2pst.py'], name = "EML2PST", version = "0.1", description = "A simple EML to PST conversion utility", options={"py2exe": py2exe_options}, )
def main(): setupAndReadConfigFile() if canCompile(): preprocessor() if "--all" in initialArgs: removeCFiles() removeCompiledFiles() compileCythonFiles() writeCompilationInfoFile() if "--export" in initialArgs: export() if not "--nocopy" in initialArgs: if os.path.isdir(config["addonsDirectory"]): copyToBlender() else: print("The path to Blenders addon directory does not exist") print("The current addons directory is: " + config["addonsDirectory"]) print("Please correct the config.py file.")
def setupAndReadConfigFile(): if not os.path.isfile(configPath) and os.path.isfile(defaultConfigPath): shutil.copyfile(defaultConfigPath, configPath) print("Copied the config.default.py file to config.py") print("Please change it manually if needed.") print("Note: git ignores it, so depending on the settings of your editor") print(" it might not be shown inside it.\n\n") if os.path.isfile(configPath): configCode = readFile(configPath) exec(configCode, config, config) else: print("Cannot find any of these files: config.py, config.default.py ") print("Make sure that at least the config.default.py exists.") print("Maybe you have to clone the repository again.") sys.exit()
def execute_makefile_commands(commands, alias, verbose=False): cmds = commands[alias] for cmd in cmds: # Parse string in a shell-like fashion # (incl quoted strings and comments) parsed_cmd = shlex.split(cmd, comments=True) # Execute command if not empty (ie, not just a comment) if parsed_cmd: if verbose: print("Running command: " + cmd) # Launch the command and wait to finish (synchronized call) check_call(parsed_cmd) # Main setup.py config # # Get version from pymake/_version.py
def get_module_hierarchy(directory): packages = {} allowed_extensions = ('.py', '.pyx', '.pxd') pycache = os.path.sep + '__pycache__' for directory, _, files in os.walk(directory): if directory.endswith(pycache): continue package_name = directory.replace(os.path.sep, '.') package = packages.setdefault(package_name, {}) for filename in files: module_name, file_ext = os.path.splitext(filename) if file_ext not in allowed_extensions: continue package.setdefault(module_name, []).append(file_ext) for module_name, extensions in list(package.items()): if '.pyx' not in extensions and '.py' not in extensions: del package[module_name] return packages
def extract_module_types(packages): py_modules = [] ext_modules = [] for package_name, package in packages.items(): if package_name in ('pytouhou.ui', 'pytouhou.ui.sdl'): package_args = sdl_args elif package_name == 'pytouhou.ui.opengl': package_args = opengl_args else: package_args = {} for module_name, extensions in package.items(): fully_qualified_name = '%s.%s' % (package_name, module_name) if '.pyx' in extensions or '.pxd' in extensions or compile_everything: if fully_qualified_name == 'pytouhou.lib.sdl': compile_args = sdl_args else: compile_args = package_args ext = 'pyx' if '.pyx' in extensions else 'py' source = '%s.%s' % (fully_qualified_name.replace('.', os.path.sep), ext) ext_modules.append(Extension(fully_qualified_name, [source], **compile_args)) else: py_modules.append(fully_qualified_name) return py_modules, ext_modules
def get_version(*file_paths): """Retrieves the version from tigerleaflet/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def get_version(*file_paths): """Retrieves the version from plugs_mail/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def get_version(*file_paths): """Retrieves the version from shibauth_rit/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def get_version(): version_file = open(path.join('csv_export', '__init__.py'), encoding='utf-8').read() version_match = re.search('__version__ = [\'"]([0-9]+\.[0-9]+\.[0-9]+)[\'"]', version_file, re.MULTILINE) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def get_version(*file_paths): """Retrieves the version from djangocms_spa_vue_js/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def test_run_setup_provides_file(self): # Make sure the script can use __file__; if that's missing, the test # setup.py script will raise NameError. distutils.core.run_setup( self.write_setup(setup_using___file__))
def setUp(self): # PyPIRCCommandTestCase creates a temp dir already # and put it in self.tmp_dir super(SDistTestCase, self).setUp() # setting up an environment self.old_path = os.getcwd() os.mkdir(join(self.tmp_dir, 'somecode')) os.mkdir(join(self.tmp_dir, 'dist')) # a package, and a README self.write_file((self.tmp_dir, 'README'), 'xxx') self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#') self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY) os.chdir(self.tmp_dir)
def get_cmd(self, metadata=None): """Returns a cmd""" if metadata is None: metadata = {'name': 'fake', 'version': '1.0', 'url': 'xxx', 'author': 'xxx', 'author_email': 'xxx'} dist = Distribution(metadata) dist.script_name = 'setup.py' dist.packages = ['somecode'] dist.include_package_data = True cmd = sdist(dist) cmd.dist_dir = 'dist' return dist, cmd
def test_manifest_comments(self): # make sure comments don't cause exceptions or wrong includes contents = dedent("""\ # bad.py #bad.py good.py """) dist, cmd = self.get_cmd() cmd.ensure_finalized() self.write_file((self.tmp_dir, cmd.manifest), contents) self.write_file((self.tmp_dir, 'good.py'), '# pick me!') self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") cmd.run() self.assertEqual(cmd.filelist.files, ['good.py'])
def test_suite(): import unittest loader = unittest.TestLoader() suite = loader.discover('.', pattern='test_*.py') return suite
def get_version(*file_paths): """Retrieves the version from shared_schema_tenants/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def get_version(*file_paths): """Retrieves the version from django_pwned_passwords/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def generate_cython(): cwd = os.path.abspath(os.path.dirname(__file__)) print("Cythonizing sources") p = subprocess.call([sys.executable, os.path.join(cwd, 'tools', 'cythonize.py'), 'pyfunt'], cwd=cwd) if p != 0: raise RuntimeError("Running cythonize failed!")
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('pyfunt') config.add_data_files(('pyfunt', '*.txt')) config.get_version('pyfunt/version.py') return config
def get_version(*file_paths): """Retrieves the version from migraph/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
def get_version(): """Obtain the version number""" import imp mod = imp.load_source('version', os.path.join(PACKAGE_NAME, 'version.py')) return mod.__version__ # Documentation building command
def ROOT(): import pkg_resources try: dist = pkg_resources.get_distribution('capnpy') except pkg_resources.DistributionNotFound: raise ValueError("Cannot find the capnpy distribution: " "please run setup.py install. " "If you are running the tests from the checkout, " "please run setup.py egg_info") # return py.path.local(dist.location)
def test_simple(self): self.write("example.capnp", """ @0xbf5147cbbecf40c1; struct Point { x @0: Int64; y @1: Int64; } """) outfile = self.compile("example.capnp") assert outfile.exists() if self.pyx: assert outfile == self.tmpdir.join('example.pyx') else: assert outfile == self.tmpdir.join('example.py')
def test_setup_build(self, monkeypatch, ROOT): self.write("example.capnp", """ @0xbf5147cbbecf40c1; struct Point { x @0: Int64; y @1: Int64; } """) self.write("setup.py", """ import sys sys.path.insert(0, '{root}') from distutils.core import setup from capnpy.compiler.distutils import capnpify exts = capnpify("*.capnp", pyx={pyx}) setup(name='foo', version='1.0', ext_modules = exts, ) """, root=ROOT, pyx=self.pyx) # monkeypatch.chdir(self.tmpdir) ret = os.system('%s setup.py build_ext --inplace' % sys.executable) assert ret == 0 if self.pyx: outfile = self.tmpdir.join('example' + self.so_file_extension) else: outfile = self.tmpdir.join('example.py') # assert outfile.check(file=True)
def test_setuptools_build(self, monkeypatch, ROOT): self.write("example.capnp", """ @0xbf5147cbbecf40c1; struct Point { x @0: Int64; y @1: Int64; } """) self.write("setup.py", """ import sys sys.path.insert(0, '{root}') from setuptools import setup setup(name='foo', version='1.0', capnpy_options=dict(pyx={pyx}), capnpy_schemas=['example.capnp'], ) """, root=ROOT, pyx=self.pyx) # monkeypatch.chdir(self.tmpdir) ret = os.system('%s setup.py build_ext --inplace' % sys.executable) assert ret == 0 if self.pyx: outfile = self.tmpdir.join('example' + self.so_file_extension) else: outfile = self.tmpdir.join('example.py') assert outfile.check(file=True) # # make sure that SOURCES.txt does not contain absolute paths, which # break things on windows ret = os.system('%s setup.py egg_info' % sys.executable) assert ret == 0 SOURCES = self.tmpdir.join('foo.egg-info', 'SOURCES.txt') for line in SOURCES.readlines(): assert not line.startswith('/')