def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'msi') short_version = get_python_version() if (not self.target_version) and self.distribution.has_ext_modules(): self.target_version = short_version if self.target_version: self.versions = [self.target_version] if not self.skip_build and self.distribution.has_ext_modules()\ and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,) else: self.versions = list(self.all_versions) self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'), ('plat_name', 'plat_name'), ) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script self.install_script_key = None
def run(self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 log.info('installing to %s' % self.bdist_dir) self.run_command('install') archive_basename = '%s.%s' % (self.distribution.get_fullname(), self.plat_name) if os.name == 'os2': archive_basename = archive_basename.replace(':', '-') pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: archive_root = self.bdist_dir elif self.distribution.has_ext_modules() and install.install_base != install.install_platbase: raise DistutilsPlatformError, "can't make a dumb built distribution where base and platbase are different (%s, %s)" % (repr(install.install_base), repr(install.install_platbase)) else: archive_root = os.path.join(self.bdist_dir, ensure_relative(install.install_base)) filename = self.make_archive(pseudoinstall_root, self.format, root_dir=archive_root, owner=self.owner, group=self.group) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append(('bdist_dumb', pyversion, filename)) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run)
def finalize_options(self): self.set_undefined_options("bdist", ("skip_build", "skip_build")) if self.bdist_dir is None: if self.skip_build and self.plat_name: # If build is skipped and plat_name is overridden, bdist will # not see the correct 'plat_name' - so set that up manually. bdist = self.distribution.get_command_obj("bdist") bdist.plat_name = self.plat_name # next the command will be initialized using that name bdist_base = self.get_finalized_command("bdist").bdist_base self.bdist_dir = os.path.join(bdist_base, "wininst") if not self.target_version: self.target_version = "" if not self.skip_build and self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, "target version can only be %s, or the '--skip-build'" " option must be specified" % ( short_version, ) self.target_version = short_version self.set_undefined_options("bdist", ("dist_dir", "dist_dir"), ("plat_name", "plat_name")) if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, "install_script '%s' not found in scripts" % self.install_script
def main(): ''' main function ''' parser = argparse.ArgumentParser(description='lvdb wrapper for gdb. Assumes .gdbinit contains at least "set logging on."') parser.add_argument("fname", help='a binary that to be called with gdb') parser.add_argument("-d", "--debug", action="store_true", help="whether to output debugging information in gdb_monitor.log") args = parser.parse_args() # start monitor with same version of python in the background # this is in case the default system version (say 2.6) does not have # IPython installed python_bin = 'python' + str(sysconfig.get_python_version()) pid = subprocess.Popen([python_bin, '-c', "import lvdb; lvdb.monitor_gdb_file({})".format(args.debug)]).pid # start gdb (waiting until it exits) subprocess.call(['gdb', '-x', '.gdbinit', args.fname]) # kill the gdb monitor and remove temporary files subprocess.call(['kill', str(pid)]) for f in ['.debug_gdb_objs', '.debug_location', '.debug_breakpoint']: try: os.remove(f) except OSError: pass
def get_install_args( self, global_options, # type: Sequence[str] record_filename, # type: str root, # type: Optional[str] prefix, # type: Optional[str] pycompile # type: bool ): # type: (...) -> List[str] install_args = [sys.executable, "-u"] install_args.append('-c') install_args.append(SETUPTOOLS_SHIM % self.setup_py) install_args += list(global_options) + \ ['install', '--record', record_filename] install_args += ['--single-version-externally-managed'] if root is not None: install_args += ['--root', root] if prefix is not None: install_args += ['--prefix', prefix] if pycompile: install_args += ["--compile"] else: install_args += ["--no-compile"] if running_under_virtualenv(): py_ver_str = 'python' + sysconfig.get_python_version() install_args += ['--install-headers', os.path.join(sys.prefix, 'include', 'site', py_ver_str, self.name)] return install_args
def finalize_options(self): self.set_undefined_options("bdist", ("skip_build", "skip_build")) if self.bdist_dir is None: bdist_base = self.get_finalized_command("bdist").bdist_base self.bdist_dir = os.path.join(bdist_base, "msi") short_version = get_python_version() if not self.target_version and self.distribution.has_ext_modules(): self.target_version = short_version if self.target_version: self.versions = [self.target_version] if not self.skip_build and self.distribution.has_ext_modules() and self.target_version != short_version: raise DistutilsOptionError, "target version can only be %s, or the '--skip-build' option must be specified" % ( short_version, ) else: self.versions = list(self.all_versions) self.set_undefined_options("bdist", ("dist_dir", "dist_dir"), ("plat_name", "plat_name")) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, "install_script '%s' not found in scripts" % self.install_script self.install_script_key = None return
def sysconfig2(): # import sysconfig module - Provide access to Python’s configuration information import sysconfig # returns an installation path corresponding to the path name print("Path Name : ", sysconfig.get_path("stdlib")) print() # returns a string that identifies the current platform. print("Current Platform : ", sysconfig.get_platform()) print() # returns the MAJOR.MINOR Python version number as a string print("Python Version Number : ", sysconfig.get_python_version()) print() # returns a tuple containing all path names print("Path Names : ", sysconfig.get_path_names()) print() # returns a tuple containing all schemes print("Scheme Names : ", sysconfig.get_scheme_names()) print() # returns the value of a single variable name. print("Variable name LIBDIR : ", sysconfig.get_config_var('LIBDIR')) # returns the value of a single variable name. print("Variable name LIBDEST : ", sysconfig.get_config_var('LIBDEST'))
def test_editable_egg_conflict(tmpdir): conflicting_package = tmpdir / 'tmp/conflicting_package' many_versions_package_2 = tmpdir / 'tmp/many_versions_package_2' from shutil import copytree copytree( str(T.TOP / 'tests/testing/packages/conflicting_package'), str(conflicting_package), ) copytree( str(T.TOP / 'tests/testing/packages/many_versions_package_2'), str(many_versions_package_2), ) with many_versions_package_2.as_cwd(): from sys import executable as python T.run(python, 'setup.py', 'bdist_egg', '--dist-dir', str(conflicting_package)) with tmpdir.as_cwd(): T.requirements('-r %s/requirements.d/coverage.txt' % T.TOP) T.venv_update() T.requirements('-e %s' % conflicting_package) with pytest.raises(CalledProcessError) as excinfo: T.venv_update() assert excinfo.value.returncode == 1 out, err = excinfo.value.result err = T.strip_coverage_warnings(err) assert err == '' out = T.uncolor(out) expected = '\nSuccessfully installed many-versions-package conflicting-package\n' assert expected in out rest = out.rsplit(expected, 1)[-1] if True: # :pragma:nocover:pylint:disable=using-constant-test # Debian de-vendorizes the version of pip it ships try: from sysconfig import get_python_version except ImportError: # <= python2.6 from distutils.sysconfig import get_python_version assert ( '''\ Cleaning up... Error: version conflict: many-versions-package 2 (tmp/conflicting_package/many_versions_package-2-py{0}.egg)''' ''' <-> many-versions-package<2 (from conflicting-package==1->-r requirements.txt (line 1)) Storing debug log for failure in {1}/home/.pip/pip.log Something went wrong! Sending 'venv' back in time, so make knows it's invalid. '''.format(get_python_version(), tmpdir) ) == rest assert_venv_marked_invalid(tmpdir.join('venv'))
def _tagged_ext_name(base): uname = platform.uname() tags = ( grpc_version.VERSION, 'py{}'.format(sysconfig.get_python_version()), uname[0], uname[4], ) ucs = 'ucs{}'.format(sysconfig.get_config_var('Py_UNICODE_SIZE')) return '{base}-{tags}-{ucs}'.format( base=base, tags='-'.join(tags), ucs=ucs)
def run(self): if not self.skip_build: self.run_command('build') install = self.get_reinitialized_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 log.info("installing to %s" % self.bdist_dir) self.run_command('install') # And make an archive relative to the root of the # pseudo-installation tree. archive_basename = "%s.%s" % (self.distribution.get_fullname(), self.plat_name) # OS/2 objects to any ":" characters in a filename (such as when # a timestamp is used in a version) so change them to hyphens. if os.name == "os2": archive_basename = archive_basename.replace(":", "-") pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: archive_root = self.bdist_dir else: if (self.distribution.has_ext_modules() and (install.install_base != install.install_platbase)): raise DistutilsPlatformError, \ ("can't make a dumb built distribution where " "base and platbase are different (%s, %s)" % (repr(install.install_base), repr(install.install_platbase))) else: archive_root = os.path.join( self.bdist_dir, self._ensure_relative(install.install_base)) # Make the archive filename = self.make_archive(pseudoinstall_root, self.format, root_dir=archive_root, owner=self.owner, group=self.group) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append(('bdist_dumb', pyversion, filename)) if not self.keep_temp: if self.dry_run: log.info('Removing %s' % self.bdist_dir) else: rmtree(self.bdist_dir)
def get_python_version(compat): """Return the version of Python that an app will use. Based on the compat level. """ if compat < 5: return '2.7' if sys.version_info.major == 3: return sysconfig.get_python_version() return subprocess.check_output(( 'python3', '-c', 'import sysconfig; print(sysconfig.get_python_version())' )).strip()
def create_ve( app_dir, python_version, platform, pypi=None, req_file='requirements.txt', verify_req_install=True): log.info('Building virtualenv') ve_dir = os.path.join(app_dir, 'virtualenv') ve_python = os.path.join(ve_dir, 'bin', 'python') req_file = os.path.join(os.path.abspath(app_dir), req_file) # The venv module makes a lot of our reclocateability problems go away, so # we only use the virtualenv library on Python 2. if python_version.startswith('3.'): subprocess.check_call(( 'python%s' % python_version, '-m', 'venv', ve_dir)) pip_version = subprocess.check_output(( ve_python, '-c', 'import ensurepip; print(ensurepip.version())')) if parse_version(pip_version) < parse_version('9'): pip_install(ve_dir, pypi, '-U', 'pip') pip_install(ve_dir, pypi, 'wheel') elif python_version == sysconfig.get_python_version(): virtualenv.create_environment(ve_dir, site_packages=False) else: subprocess.check_call(( sys.executable, virtualenv.__file__.rstrip('c'), '-p', 'python%s' % python_version, '--no-site-packages', ve_dir)) log.info('Installing requirements') pip_install(ve_dir, pypi, '-r', req_file) if verify_req_install: log.info('Verifying requirements were met') check_requirements(ve_dir) relocateable_ve(ve_dir, python_version) ve_id = get_id(os.path.join(app_dir, req_file), python_version, platform) with open(os.path.join(ve_dir, '.hash'), 'w') as f: f.write(ve_id) f.write('\n') log.info('Building virtualenv tarball') cwd = os.getcwd() os.chdir(app_dir) t = tarfile.open('virtualenv.tar.gz', 'w:gz') try: t.add('virtualenv') finally: t.close() os.chdir(cwd)
def print_benchmarks(times): ''' Pretty print for the benchmark results, with a detailed CSV at the end. ''' print('\nmazelib benchmarking') print(datetime.now().strftime('%Y-%m-%d %H:%M')) print('Python version: ' + get_python_version()) print('\nTotal Time (seconds): %.5f\n' % sum([sum(times_row) for times_row in times])) print('\nmaze size,' + ','.join([str(s) for s in SIZES])) for row in range(len(times)): method = GENERATORS[row] + '-' + SOLVERS[row] + ',' print(method + ','.join(['%.5f' % time for time in times[row]]))
def finalize_options(self): orig_bdist_egg.finalize_options(self) # Redo the calculation of the egg's filename since we always have # extension modules, but they are not built by setuptools so it # doesn't know about them. from pkg_resources import Distribution from sysconfig import get_python_version basename = Distribution( None, None, self.ei_cmd.egg_name, self.ei_cmd.egg_version, get_python_version(), self.plat_name ).egg_name() self.egg_output = os.path.join(self.dist_dir, basename+'.egg')
def get_exe_bytes (self): cur_version = get_python_version() bv=9.0 directory = os.path.dirname(_bdist_file) if self.plat_name != 'win32' and self.plat_name[:3] == 'win': sfix = self.plat_name[3:] else: sfix = '' filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) f = open(filename, "rb") try: return f.read() finally: f.close()
def get(self): retVal = {} retVal["success"] = True retVal["message"] = "OK" retVal["commit"] = os.environ["COMMIT"] if "COMMIT" in os.environ else "dev" retVal["timestamp"] = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") retVal["lastmod"] = os.environ["LASTMOD"] if "LASTMOD" in os.environ else "dev" retVal["tech"] = "Python %d.%d.%d" % (sys.version_info.major, sys.version_info.minor, sys.version_info.micro) retVal["version"] = "%s (%s)" % (platform.python_version(), platform.python_implementation()) add_if_exists(retVal, "platform.machine()", platform.machine()) add_if_exists(retVal, "platform.node()", platform.node()) #IOError: add_if_exists(retVal, "platform.platform()", platform.platform()) add_if_exists(retVal, "platform.processor()", platform.processor()) add_if_exists(retVal, "platform.python_branch()", platform.python_branch()) add_if_exists(retVal, "platform.python_build()", platform.python_build()) add_if_exists(retVal, "platform.python_compiler()", platform.python_compiler()) add_if_exists(retVal, "platform.python_implementation()", platform.python_implementation()) add_if_exists(retVal, "platform.python_version()", platform.python_version()) add_if_exists(retVal, "platform.python_revision()", platform.python_revision()) add_if_exists(retVal, "platform.release()", platform.release()) add_if_exists(retVal, "platform.system()", platform.system()) add_if_exists(retVal, "platform.version()", platform.version()) add_if_exists(retVal, "platform.uname()", platform.uname()) add_if_exists(retVal, "sysconfig.get_platform()", sysconfig.get_platform()) add_if_exists(retVal, "sysconfig.get_python_version()", sysconfig.get_python_version()) add_if_exists(retVal, "sys.byteorder", sys.byteorder) add_if_exists(retVal, "sys.copyright", sys.copyright) add_if_exists(retVal, "sys.getdefaultencoding()", sys.getdefaultencoding()) add_if_exists(retVal, "sys.getfilesystemencoding()", sys.getfilesystemencoding()) add_if_exists(retVal, "sys.maxint", sys.maxint) add_if_exists(retVal, "sys.maxsize", sys.maxsize) add_if_exists(retVal, "sys.maxunicode", sys.maxunicode) add_if_exists(retVal, "sys.version", sys.version) self.response.headers['Content-Type'] = 'text/plain' callback = self.request.get('callback') if len(callback) == 0 or re.match("[a-zA-Z][-a-zA-Z0-9_]*$", callback) is None: self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET' self.response.headers['Access-Control-Max-Age'] = '604800' # 1 week self.response.out.write(json.dumps(retVal, separators=(',', ':'))) else: self.response.out.write(callback) self.response.out.write("(") self.response.out.write(json.dumps(retVal, separators=(',', ':'))) self.response.out.write(");")
def run(self): if sys.platform != 'win32' and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries()): raise DistutilsPlatformError('distribution contains extensions and/or C libraries; must be compiled on a Windows 32 platform') if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install.plat_name = self.plat_name install_lib = self.reinitialize_command('install_lib') install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): target_version = self.target_version if not target_version: if not self.skip_build: raise AssertionError('Should have already checked this') target_version = sys.version[0:3] plat_specifier = '.%s-%s' % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'): value = string.upper(key) if key == 'headers': value = value + '/Include/$dist_name' setattr(install, 'install_' + key, value) log.info('installing to %s', self.bdist_dir) install.ensure_finalized() sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] from tempfile import mktemp archive_basename = mktemp() fullname = self.distribution.get_fullname() arcname = self.make_archive(archive_basename, 'zip', root_dir=self.bdist_dir) self.create_exe(arcname, fullname, self.bitmap) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append(('bdist_wininst', pyversion, self.get_installer_filename(fullname))) log.debug("removing temporary file '%s'", arcname) os.remove(arcname) self.keep_temp or remove_tree(self.bdist_dir, dry_run=self.dry_run)
def get_exe_bytes(self): from distutils.msvccompiler import get_build_version # If a target-version other than the current version has been # specified, then using the MSVC version from *this* build is no good. # Without actually finding and executing the target version and parsing # its sys.version, we just hard-code our knowledge of old versions. # NOTE: Possible alternative is to allow "--target-version" to # specify a Python executable rather than a simple version string. # We can then execute this program to obtain any info we need, such # as the real sys.version string for the build. cur_version = get_python_version() if self.target_version and self.target_version != cur_version: # If the target version is *later* than us, then we assume they # use what we use # string compares seem wrong, but are what sysconfig.py itself uses if self.target_version > cur_version: bv = get_build_version() else: if self.target_version < "2.4": bv = 6.0 else: bv = 7.1 else: # for current version - use authoritative check. bv = get_build_version() # wininst-x.y.exe is in the same directory as this file directory = os.path.dirname(__file__) # we must use a wininst-x.y.exe built with the same C compiler # used for python. XXX What about mingw, borland, and so on? # if plat_name starts with "win" but is not "win32" # we want to strip "win" and leave the rest (e.g. -amd64) # for all other cases, we don't want any suffix if self.plat_name != "win32" and self.plat_name[:3] == "win": sfix = self.plat_name[3:] else: sfix = "" filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) f = open(filename, "rb") try: return f.read() finally: f.close()
def setUp(self): super(ApplicationTestCase, self).setUp() shutil.copy( os.path.join(FIXTURES_DIR, 'config.py'), self.tmppath('config.py')) store = LocalRepositoryStore(self.mkdir('artifacts')) self.repo = Repository(store) self.app = Application('test', self.tmppath('config.py')) self.test_ve_tar_path = self._data_path('deploy-ve/virtualenv.tar.gz') self.test_req_path = self._data_path('deploy-ve/requirements.txt') self.test_ve_path = self._data_path('deploy-ve') if not os.path.exists(self.test_ve_tar_path): self._create_test_ve() self._deploy_ve_id = virtualenv.get_id( self.test_req_path, sysconfig.get_python_version(), 'test')
def __init__(self, dev_install, debug_level=None, mark_read=None): if dev_install: self.conf_dir = os.path.expanduser('~/.democraticd/') default_log = os.path.join(self.conf_dir, 'democraticd.log') else: self.conf_dir = '/etc/democraticd/' default_log = '/var/log/democraticd.log' self.packages_dir = os.path.join(self.conf_dir, 'packages') self.debs_dir = os.path.join(self.conf_dir, 'debs') self.pull_requests_dir = os.path.join(self.conf_dir, 'pull-requests') self.json_extension = '.json' filename = os.path.join(self.conf_dir, 'config.json') if not os.path.exists(filename): raise Exception('Not installed properly - ' + filename + ' does not exist') with open(filename, 'rt') as f: file_values = json.loads(f.read() or '{}') self.port = file_values.get('port', 9999) if debug_level == None: debug_level = file_values.get('debug_level', DebugLevel.ESSENTIAL) self.debug_level = debug_level if mark_read == None: mark_read = file_values.get('mark_read', True) self.mark_read = mark_read self.uid = file_values.get('uid', 0) self.gid = file_values.get('gid', 0) self.euid = file_values.get('euid', 1000) self.egid = file_values.get('egid', 1000) self.git_name = file_values.get('git_name', 'Democratic Daemon') self.git_email = file_values.get('git_email', '*****@*****.**') self.log_filename = file_values.get('log_file', default_log) self.python = 'python' + sysconfig.get_python_version()[0] self.module_dir = '.' if sys.argv[0]: self.module_dir = os.path.join(os.path.dirname(sys.argv[0]), '..') self.module_dir = os.path.abspath(self.module_dir)
def get_libraries(include_python_lib=False): libraries = [] if sys.version_info[0] == 3 and sys.version_info[1] >= 5 and is_msvc(): # https://stackoverflow.com/questions/32418766/c-unresolved-external-symbol-sprintf-and-sscanf-in-visual-studio-2015 libraries = ['legacy_stdio_definitions'] if is_msvc(): link_py = 'python{0}{1}'.format(*sys.version_info[0:2]) else: if PY2: link_py_fmt = 'python{version}' else: link_py_fmt = 'python{version}m' link_py = link_py_fmt.format(version=sysconfig.get_python_version()) if include_python_lib: libraries.append(link_py) return libraries
def test_editable_egg_conflict(tmpdir): conflicting_package = tmpdir / 'tmp/conflicting_package' many_versions_package_2 = tmpdir / 'tmp/many_versions_package_2' from shutil import copytree copytree( str(T.TOP / 'tests/testing/packages/conflicting_package'), str(conflicting_package), ) copytree( str(T.TOP / 'tests/testing/packages/many_versions_package_2'), str(many_versions_package_2), ) with many_versions_package_2.as_cwd(): from sys import executable as python T.run(python, 'setup.py', 'bdist_egg', '--dist-dir', str(conflicting_package)) with tmpdir.as_cwd(): T.enable_coverage() T.requirements('-e %s' % conflicting_package) with pytest.raises(CalledProcessError) as excinfo: T.venv_update() assert excinfo.value.returncode == 1 out, err = excinfo.value.result err = T.strip_coverage_warnings(err) err = T.strip_pip_warnings(err) assert err == ( 'Error: version conflict: many-versions-package 2 ' '(tmp/conflicting_package/many_versions_package-2-py{}.egg) ' '<-> many_versions_package<2 ' '(from conflicting-package==1->-r requirements.txt (line 1))\n'.format( get_python_version(), ) ) out = T.uncolor(out) assert_something_went_wrong(out) assert_venv_marked_invalid(tmpdir.join('venv'))
def get(self): retVal = {} retVal["success"] = True retVal["message"] = "OK" retVal["version"] = "%s (%s)" % (platform.python_version(), platform.python_implementation()) add_if_exists(retVal, "platform.machine()", platform.machine()) add_if_exists(retVal, "platform.node()", platform.node()) #IOError: add_if_exists(retVal, "platform.platform()", platform.platform()) add_if_exists(retVal, "platform.processor()", platform.processor()) add_if_exists(retVal, "platform.python_branch()", platform.python_branch()) add_if_exists(retVal, "platform.python_build()", platform.python_build()) add_if_exists(retVal, "platform.python_compiler()", platform.python_compiler()) add_if_exists(retVal, "platform.python_implementation()", platform.python_implementation()) add_if_exists(retVal, "platform.python_version()", platform.python_version()) add_if_exists(retVal, "platform.python_revision()", platform.python_revision()) add_if_exists(retVal, "platform.release()", platform.release()) add_if_exists(retVal, "platform.system()", platform.system()) add_if_exists(retVal, "platform.version()", platform.version()) add_if_exists(retVal, "platform.uname()", platform.uname()) add_if_exists(retVal, "sysconfig.get_platform()", sysconfig.get_platform()) add_if_exists(retVal, "sysconfig.get_python_version()", sysconfig.get_python_version()) add_if_exists(retVal, "sys.byteorder", sys.byteorder) add_if_exists(retVal, "sys.copyright", sys.copyright) add_if_exists(retVal, "sys.getdefaultencoding()", sys.getdefaultencoding()) add_if_exists(retVal, "sys.getfilesystemencoding()", sys.getfilesystemencoding()) add_if_exists(retVal, "sys.maxint", sys.maxint) add_if_exists(retVal, "sys.maxsize", sys.maxsize) add_if_exists(retVal, "sys.maxunicode", sys.maxunicode) add_if_exists(retVal, "sys.version", sys.version) self.response.headers['Content-Type'] = 'text/plain' callback = self.request.get('callback') if len(callback) == 0 or re.match("[a-zA-Z][-a-zA-Z0-9_]*$", callback) is None: self.response.out.write(json.dumps(retVal, separators=(',', ':'))) else: self.response.out.write(callback) self.response.out.write("(") self.response.out.write(json.dumps(retVal, separators=(',', ':'))) self.response.out.write(");")
def generate(env, **kwargs): """Add Builders and construction variables to the Environment.""" if not 'python' in env['TOOLS'][:-1]: env.Tool('system') env.Tool('prefix') PYTHON_VERSION = sysconfig.get_python_version() SYSTEM = env['SYSTEM'] if SYSTEM == 'win': env.AppendUnique(LIBS = ['python' + PYTHON_VERSION.replace('.', '')], CPPPATH = [os.path.join('$PREFIX', '..', 'include')]) elif PYTHON_VERSION == '2.7': env.AppendUnique(CPPPATH = [os.path.join('$PREFIX', 'include', 'python' + PYTHON_VERSION)], LIBS = ['python' + PYTHON_VERSION]) elif PYTHON_VERSION in ['3.6', '3.7']: env.AppendUnique(CPPPATH = [os.path.join('$PREFIX', 'include', 'python' + PYTHON_VERSION + 'm')], LIBS = ['python' + PYTHON_VERSION + 'm']) else: raise NotImplementedError('Python ' + PYTHON_VERSION) if SYSTEM == 'win': env['SP_DIR'] = os.path.join('$PREFIX', '..', 'Lib', 'site-packages') else: env['SP_DIR'] = os.path.join('$PREFIX', 'lib', 'python' + PYTHON_VERSION, 'site-packages') def PythonPackage(env, **kwargs): pattern = kwargs.pop('pattern', None) packages = {kwarg : Path(env.Dir(kwargs[kwarg]).srcnode().abspath).walkfiles(pattern) for kwarg in kwargs} targets = [] SP_DIR = env['SP_DIR'] for package in packages: for source in packages[package]: if not source.ext in ['.lib', '.exp', '.so', '.dll']: directory = os.path.join('$SP_DIR', *package.split('.')) directory = os.path.join(directory, source.relpath(env.Dir(kwargs[package]).srcnode().abspath).parent) targets.append(env.Install(directory, source.abspath())) return targets env.AddMethod(PythonPackage)
def make_distribution(self): """Minimize path lenght to avoid windows issues.""" # Copied from distutils.command.sdist.sdist.make_distribution # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_version() base_name = os.path.join(self.dist_dir, options.get_egg_name(self.distribution) + ".msdeploy") self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create file = self.make_archive(base_name, "zip", base_dir=base_dir, owner=self.owner, group=self.group) archive_files.append(file) pyversion = sysconfig.get_python_version() self.distribution.dist_files.append(("bdist_dumb", pyversion, file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run)
def finalize_options(self): ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info") self.egg_info = ei_cmd.egg_info if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'egg') if self.plat_name is None: self.plat_name = get_build_platform() self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.egg_output is None: # Compute filename of the output egg basename = Distribution( None, None, ei_cmd.egg_name, ei_cmd.egg_version, get_python_version(), self.distribution.has_ext_modules() and self.plat_name ).egg_name() self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
def finalize_options(self): ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info") self.egg_info = ei_cmd.egg_info if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'egg') if self.plat_name is None: self.plat_name = get_build_platform() self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.egg_output is None: # Compute filename of the output egg basename = Distribution( None, None, ei_cmd.egg_name, ei_cmd.egg_version, get_python_version(), self.distribution.has_ext_modules() and self.plat_name).egg_name() self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
def build_linux_launcher(args, launcher_dir='.', for_bundle=False, sh_launcher=False): cflags = '-Wall -Werror -fpie'.split() libs = [] if args.profile: cflags.append('-DWITH_PROFILER'), cflags.append('-g') libs.append('-lprofiler') else: cflags.append('-O3') if for_bundle: cflags.append('-DFOR_BUNDLE') cflags.append('-DPYVER="{}"'.format(sysconfig.get_python_version())) elif sh_launcher: cflags.append('-DFOR_LAUNCHER') pylib = get_python_flags(cflags) exe = 'kitty-profile' if args.profile else 'kitty' cmd = [env.cc] + cflags + [ 'linux-launcher.c', '-o', os.path.join(launcher_dir, exe) ] + libs + pylib run_tool(cmd)
def get_exe_bytes(self): from distutils.msvccompiler import get_build_version cur_version = get_python_version() if self.target_version and self.target_version != cur_version: if self.target_version > cur_version: bv = get_build_version() elif self.target_version < '2.4': bv = 6.0 else: bv = 7.1 else: bv = get_build_version() directory = os.path.dirname(__file__) if self.plat_name != 'win32' and self.plat_name[:3] == 'win': sfix = self.plat_name[3:] else: sfix = '' filename = os.path.join(directory, 'wininst-%.1f%s.exe' % (bv, sfix)) f = open(filename, 'rb') try: return f.read() finally: f.close()
def finalize_options (self): self.set_undefined_options('bdist', ('skip_build', 'skip_build')) if self.bdist_dir is None: if self.skip_build and self.plat_name: # If build is skipped and plat_name is overridden, bdist will # not see the correct 'plat_name' - so set that up manually. bdist = self.distribution.get_command_obj('bdist') bdist.plat_name = self.plat_name # next the command will be initialized using that name bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'wininst') if not self.target_version: self.target_version = "" if not self.skip_build and self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip-build'" \ " option must be specified" % (short_version,) self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'), ('plat_name', 'plat_name'), ) if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script
def get_install_args( self, global_options, # type: Sequence[str] record_filename, # type: str root, # type: Optional[str] prefix, # type: Optional[str] pycompile, # type: bool ): # type: (...) -> List[str] install_args = make_setuptools_shim_args(self.setup_py_path, unbuffered_output=True) install_args += list(global_options) + [ "install", "--record", record_filename, ] install_args += ["--single-version-externally-managed"] if root is not None: install_args += ["--root", root] if prefix is not None: install_args += ["--prefix", prefix] if pycompile: install_args += ["--compile"] else: install_args += ["--no-compile"] if running_under_virtualenv(): py_ver_str = "python" + sysconfig.get_python_version() install_args += [ "--install-headers", os.path.join(sys.prefix, "include", "site", py_ver_str, self.name), ] return install_args
def _create_test_ve(self): """ Bootstrap a deploy virtualenv, for our tests This needs a PYPI that contains yodeploy """ pypi = os.environ.get('PYPI') if not pypi: import yodeploy.config deploy_settings = yodeploy.config.load_settings( yodeploy.config.find_deploy_config()) pypi = deploy_settings.build.pypi if os.path.exists(self.test_ve_path): shutil.rmtree(self.test_ve_path) os.makedirs(self.test_ve_path) yodeploy_installable = self._prep_wip_yodeploy_for_install() with open(self.test_req_path, 'w') as f: f.write('%s\n' % yodeploy_installable) virtualenv.create_ve( self.test_ve_path, sysconfig.get_python_version(), 'test', pypi, verify_req_install=False)
def deploy_ve(self): log = logging.getLogger(__name__) ve_id = virtualenv.get_id(self.deploy_path('requirements.txt'), sysconfig.get_python_version(), self.settings.artifacts.platform) ve_working = os.path.join(self.root, 'virtualenvs', 'unpack') ve_dir = os.path.join(self.root, 'virtualenvs', ve_id) tarball = os.path.join(ve_working, 'virtualenv.tar.gz') ve_unpack_root = os.path.join(ve_working, 'virtualenv') if not os.path.exists(ve_dir): log.debug('Deploying virtualenv %s', ve_id) if not os.path.exists(ve_working): os.makedirs(ve_working) virtualenv.download_ve( self.repository, self.app, ve_id, self.target, dest=tarball) extract_tar(tarball, ve_unpack_root) os.rename(ve_unpack_root, ve_dir) ve_symlink = self.deploy_path('virtualenv') if not os.path.exists(ve_symlink): os.symlink(os.path.join('..', '..', 'virtualenvs', ve_id), ve_symlink)
def finalize_options(self): self.set_undefined_options('bdist', ('skip_build', 'skip_build')) if self.bdist_dir is None: if self.skip_build and self.plat_name: bdist = self.distribution.get_command_obj('bdist') bdist.plat_name = self.plat_name bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'wininst') if not self.target_version: self.target_version = '' if not self.skip_build and self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, "target version can only be %s, or the '--skip-build' option must be specified" % (short_version,) self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'), ('plat_name', 'plat_name')) if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, "install_script '%s' not found in scripts" % self.install_script return
def make_distribution(self): """Minimize path lenght to avoid windows issues.""" # Copied from distutils.command.sdist.sdist.make_distribution # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_version() base_name = os.path.join( self.dist_dir, options.get_egg_name(self.distribution) + '.msdeploy') self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create file = self.make_archive(base_name, 'zip', base_dir=base_dir, owner=self.owner, group=self.group) archive_files.append(file) pyversion = sysconfig.get_python_version() self.distribution.dist_files.append(('bdist_dumb', pyversion, file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run)
def run(self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 log.info('installing to %s' % self.bdist_dir) self.run_command('install') archive_basename = '%s.%s' % (self.distribution.get_fullname(), self.plat_name) if os.name == 'os2': archive_basename = archive_basename.replace(':', '-') pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: archive_root = self.bdist_dir elif self.distribution.has_ext_modules( ) and install.install_base != install.install_platbase: raise DistutilsPlatformError, "can't make a dumb built distribution where base and platbase are different (%s, %s)" % ( repr(install.install_base), repr(install.install_platbase)) else: archive_root = os.path.join(self.bdist_dir, ensure_relative(install.install_base)) filename = self.make_archive(pseudoinstall_root, self.format, root_dir=archive_root, owner=self.owner, group=self.group) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append( ('bdist_dumb', pyversion, filename)) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run)
def get_install_args( self, global_options, # type: Sequence[str] record_filename, # type: str root, # type: Optional[str] prefix, # type: Optional[str] pycompile, # type: bool ): # type: (...) -> List[str] install_args = [sys.executable, "-u"] install_args.append("-c") install_args.append(SETUPTOOLS_SHIM % self.setup_py) install_args += list(global_options) + [ "install", "--record", record_filename ] install_args += ["--single-version-externally-managed"] if root is not None: install_args += ["--root", root] if prefix is not None: install_args += ["--prefix", prefix] if pycompile: install_args += ["--compile"] else: install_args += ["--no-compile"] if running_under_virtualenv(): py_ver_str = "python" + sysconfig.get_python_version() install_args += [ "--install-headers", os.path.join(sys.prefix, "include", "site", py_ver_str, self.name) ] return install_args
def language_version(self, state, args, kwargs): if args or kwargs: raise mesonlib.MesonException( 'language_version() takes no arguments.') return ModuleReturnValue(sysconfig.get_python_version(), [])
def run(self): if (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform") if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install.plat_name = self.plat_name install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) # Use a custom scheme for the zip-file, because we have to decide # at installation time which scheme to use. for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'): value = string.upper(key) if key == 'headers': value = value + '/Include/$dist_name' setattr(install, 'install_' + key, value) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] # And make an archive relative to the root of the # pseudo-installation tree. from tempfile import mktemp archive_basename = mktemp() fullname = self.distribution.get_fullname() arcname = self.make_archive(archive_basename, "zip", root_dir=self.bdist_dir) # create an exe containing the zip-file self.create_exe(arcname, fullname, self.bitmap) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append( ('bdist_wininst', pyversion, self.get_installer_filename(fullname))) # remove the zip-file again log.debug("removing temporary file '%s'", arcname) os.remove(arcname) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run)
--- setup/install.py.orig 2021-12-17 00:40:19 UTC +++ setup/install.py @@ -158,7 +158,7 @@ class Develop(Command): import sysconfig libdir = os.path.join( self.opts.staging_root, sysconfig.get_config_var('PLATLIBDIR') or 'lib', - sysconfig.get_python_version(), 'site-packages') + os.path.basename(sysconfig.get_config_var('DESTLIB') or sysconfig.get_config_var('LIBDEST') or f'python{sysconfig.get_python_version()}'), 'site-packages') try: if not os.path.exists(libdir): os.makedirs(libdir)
def get(self): retVal = {} retVal["success"] = True retVal["message"] = "OK" retVal["commit"] = os.environ[ "COMMIT"] if "COMMIT" in os.environ else "dev" retVal["timestamp"] = datetime.datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%SZ") retVal["lastmod"] = os.environ[ "LASTMOD"] if "LASTMOD" in os.environ else "dev" retVal["tech"] = "Python %d.%d.%d" % (sys.version_info.major, sys.version_info.minor, sys.version_info.micro) add_if_exists(retVal, "platform.machine()", platform.machine()) add_if_exists(retVal, "platform.node()", platform.node()) #IOError: add_if_exists(retVal, "platform.platform()", platform.platform()) add_if_exists(retVal, "platform.processor()", platform.processor()) add_if_exists(retVal, "platform.python_branch()", platform.python_branch()) add_if_exists(retVal, "platform.python_build()", platform.python_build()) add_if_exists(retVal, "platform.python_compiler()", platform.python_compiler()) add_if_exists(retVal, "platform.python_implementation()", platform.python_implementation()) add_if_exists(retVal, "platform.python_version()", platform.python_version()) add_if_exists(retVal, "platform.python_revision()", platform.python_revision()) add_if_exists(retVal, "platform.release()", platform.release()) add_if_exists(retVal, "platform.system()", platform.system()) add_if_exists(retVal, "platform.version()", platform.version()) add_if_exists(retVal, "platform.uname()", platform.uname()) add_if_exists(retVal, "sysconfig.get_platform()", sysconfig.get_platform()) add_if_exists(retVal, "sysconfig.get_python_version()", sysconfig.get_python_version()) add_if_exists(retVal, "sys.byteorder", sys.byteorder) add_if_exists(retVal, "sys.copyright", sys.copyright) add_if_exists(retVal, "sys.getdefaultencoding()", sys.getdefaultencoding()) add_if_exists(retVal, "sys.getfilesystemencoding()", sys.getfilesystemencoding()) add_if_exists(retVal, "sys.maxint", sys.maxint) add_if_exists(retVal, "sys.maxsize", sys.maxsize) add_if_exists(retVal, "sys.maxunicode", sys.maxunicode) add_if_exists(retVal, "sys.version", sys.version) if "DATABASE_URL" in os.environ: cols, rows = do_query( "SELECT version(), current_setting('server_version'), current_setting('server_version_num');", None) dbdetail = rows[0][0] if len(rows) > 0 else None dbversion = rows[0][1] if len(rows) > 0 else None dbversionnum = rows[0][2] if len(rows) > 0 else None retVal["version"] = dbversion add_if_exists(retVal, "SELECT version();", dbdetail) add_if_exists(retVal, "SELECT current_setting('server_version_num');", dbversionnum) else: add_if_exists(retVal, "Database", "NOT CONFIGURED") self.response.headers['Content-Type'] = 'text/plain' callback = self.request.get('callback') if len(callback) == 0 or re.match("[a-zA-Z][-a-zA-Z0-9_]*$", callback) is None: self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET' self.response.headers[ 'Access-Control-Max-Age'] = '604800' # 1 week self.response.out.write(json.dumps(retVal, separators=(',', ':'))) else: self.response.out.write(callback) self.response.out.write("(") self.response.out.write(json.dumps(retVal, separators=(',', ':'))) self.response.out.write(");")
def language_version(self, state, args, kwargs): return ModuleReturnValue(sysconfig.get_python_version(), [])
def python_version(self): with self.activated(): from sysconfig import get_python_version py_version = get_python_version() return py_version
def base_paths(self): """ Returns the context appropriate paths for the environment. :return: A dictionary of environment specific paths to be used for installation operations :rtype: dict .. note:: The implementation of this is borrowed from a combination of pip and virtualenv and is likely to change at some point in the future. >>> from pipenv.core import project >>> from pipenv.environment import Environment >>> env = Environment(prefix=project.virtualenv_location, is_venv=True, sources=project.sources) >>> import pprint >>> pprint.pprint(env.base_paths) {'PATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin::/bin:/usr/bin', 'PYTHONPATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'data': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'include': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'libdir': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platinclude': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'platlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platstdlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7', 'prefix': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'purelib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'scripts': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin', 'stdlib': '/home/hawk/.pyenv/versions/3.7.1/lib/python3.7'} """ prefix = make_posix(self.prefix.as_posix()) paths = {} if self._base_paths: paths = self._base_paths.copy() else: try: paths = self.get_paths() except Exception: install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix' paths = get_paths(install_scheme, vars={ 'base': prefix, 'platbase': prefix, }) current_version = get_python_version() try: for k in list(paths.keys()): if not os.path.exists(paths[k]): paths[k] = self._replace_parent_version(paths[k], current_version) except OSError: # Sometimes virtualenvs are made using virtualenv interpreters and there is no # include directory, which will cause this approach to fail. This failsafe # will make sure we fall back to the shell execution to find the real include path paths = self.get_include_path() paths.update(self.get_lib_paths()) paths["scripts"] = self.script_basedir if not paths: install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix' paths = get_paths(install_scheme, vars={ 'base': prefix, 'platbase': prefix, }) if not os.path.exists(paths["purelib"]) and not os.path.exists(paths["platlib"]): lib_paths = self.get_lib_paths() paths.update(lib_paths) paths["PATH"] = paths["scripts"] + os.pathsep + os.defpath if "prefix" not in paths: paths["prefix"] = prefix purelib = paths["purelib"] = make_posix(paths["purelib"]) platlib = paths["platlib"] = make_posix(paths["platlib"]) if purelib == platlib: lib_dirs = purelib else: lib_dirs = purelib + os.pathsep + platlib paths["libdir"] = purelib paths['PYTHONPATH'] = os.pathsep.join(["", ".", lib_dirs]) paths["libdirs"] = lib_dirs return paths
if self.plat_name is None: self.plat_name = get_build_platform() <<<<<<< HEAD self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) ======= self.set_undefined_options('bdist',('dist_dir', 'dist_dir')) >>>>>>> e4baf504ede925f4f1e07d823c9b20b3d0dbe14c if self.egg_output is None: # Compute filename of the output egg basename = Distribution( None, None, ei_cmd.egg_name, ei_cmd.egg_version, get_python_version(), self.distribution.has_ext_modules() and self.plat_name ).egg_name() <<<<<<< HEAD self.egg_output = os.path.join(self.dist_dir, basename + '.egg') ======= self.egg_output = os.path.join(self.dist_dir, basename+'.egg') >>>>>>> e4baf504ede925f4f1e07d823c9b20b3d0dbe14c
# coding=utf-8 # 使用sysconfig import sysconfig print sysconfig.get_config_var('Py_ENABLE_SHARED') print sysconfig.get_config_var('LIBDIR') print sysconfig.get_config_vars('AR', "CXX") print sysconfig.get_scheme_names() print sysconfig.get_path_names() print sysconfig.get_python_version() print sysconfig.get_platform() # return true if current python installation was built from source print sysconfig.is_python_build() print sysconfig.get_config_h_filename() print sysconfig._get_makefile_filename()
import sys from cx_Freeze import setup, Executable from pathlib import Path import sysconfig import os is_64bits = sys.maxsize > 2**32 folder = "exe.{platform}-{version}".format( platform=sysconfig.get_platform(), version=sysconfig.get_python_version()) buildfolder = Path("build", folder) # Dependencies are automatically detected, but it might need fine tuning. build_exe_options = {"packages": "Language"} # GUI applications require a different base on Windows (the default is for a # console application). base = None targetname = None targetname2 = None if sys.platform == "win32": base = "Win32GUI" targetname = "Ticker.exe" targetname2 = "Console.exe" setup( name="CPU Ticker", version="2.0", #description = "", options={"build_exe": build_exe_options}, executables=[
def Extension(name, sources, **kw): pygo, kw = _with_build_defaults(kw) # some pyx-level depends to workaround a bit lack of proper dependency # tracking in setuptools/distutils. dependv = kw.get('depends', [])[:] dependv.extend([ '%s/golang/%s' % (pygo, _) for _ in [ '_golang.pxd', 'runtime/_libgolang.pxd', 'runtime/internal/__init__.pxd', 'runtime/internal/syscall.pxd', '__init__.pxd', 'context.pxd', '_context.pxd', 'cxx.pxd', 'errors.pxd', '_errors.pxd', 'fmt.pxd', '_fmt.pxd', 'io.pxd', '_io.pxd', 'strings.pxd', 'sync.pxd', '_sync.pxd', 'time.pxd', '_time.pxd', 'os.pxd', '_os.pxd', 'os/signal.pxd', 'os/_signal.pxd', 'pyx/runtime.pxd', ] ]) kw['depends'] = dependv # workaround pip bug that for virtualenv case headers are installed into # not-searched include path. https://github.com/pypa/pip/issues/4610 # (without this e.g. "greenlet/greenlet.h" is not found) venv_inc = join(sys.prefix, 'include', 'site', 'python' + sysconfig.get_python_version()) if exists(venv_inc): kw['include_dirs'].append(venv_inc) # provide POSIX/PYPY/... defines to Cython POSIX = ('posix' in sys.builtin_module_names) PYPY = (platform.python_implementation() == 'PyPy') PY2 = (sys.version_info.major < 3) PY3 = (not PY2) pyxenv = kw.get('cython_compile_time_env', {}) pyxenv.setdefault('POSIX', POSIX) pyxenv.setdefault('PYPY', PYPY) pyxenv.setdefault('PY2', PY2) pyxenv.setdefault('PY3', PY3) gverhex = _gevent_version_hex() if gverhex is not None: pyxenv.setdefault('GEVENT_VERSION_HEX', gverhex) kw['cython_compile_time_env'] = pyxenv # XXX hack, because setuptools_dso.Extension is not Cython.Extension # del from kw to avoid "Unknown Extension options: 'cython_compile_time_env'" #ext = setuptools_dso.Extension(name, sources, **kw) pyxenv = kw.pop('cython_compile_time_env') ext = setuptools_dso.Extension(name, sources, **kw) ext.cython_compile_time_env = pyxenv return ext
def ensure_coverage_importable(): # We want to use the compiled coverage if we can from pkg_resources import get_build_platform try: # Python 2.7 or >= 3.2 from sysconfig import get_python_version except ImportError: from distutils.sysconfig import get_python_version cov_dir = os.path.join(BASE_DIR, 'third_party', 'coverage-3.7.1') cov_egg = os.path.join( cov_dir, 'dist', 'coverage-3.7.1-py%s-%s.egg' % (get_python_version(), get_build_platform())) if cov_egg not in sys.path: sys.path.insert(0, cov_egg) try: from distutils.version import StrictVersion import coverage if (StrictVersion(coverage.__version__) < StrictVersion('3.7') or not coverage.collector.CTracer): toDel = set() for m in sys.modules: if m == 'coverage' or m.startswith('coverage.'): toDel.add(m) for k in toDel: del sys.modules[k] del coverage else: return except ImportError: if sys.platform.startswith('win'): # In order to compile the coverage module on Windows we need to set the # 'VS90COMNTOOLS' environment variable. This usually point to the # installation folder of VS2008 but we can fake it to make it point to the # version of the toolchain checked in depot_tools. # # This variable usually point to the $(VsInstallDir)\Common7\Tools but is # only used to access %VS90COMNTOOLS%/../../VC/vcvarsall.bat and therefore # any valid directory respecting this structure can be used. vc_path = os.path.join(DEPOT_TOOLS_DIR, 'win_toolchain', 'vs2013_files', 'VC', 'bin') # If the toolchain isn't available then ask the user to fetch chromium in # order to install it. if not os.path.isdir(vc_path): print textwrap.dedent(""" You probably don't have the Windows toolchain in your depot_tools checkout. Install it by running: fetch chromium """) sys.exit(1) os.environ['VS90COMNTOOLS'] = vc_path try: import setuptools # pylint: disable=W0612 except ImportError: print textwrap.dedent(""" No compatible system-wide python-coverage package installed, and setuptools is not installed either. Please obtain setuptools by: Debian/Ubuntu: sudo apt-get install python-setuptools python-dev OS X: https://pypi.python.org/pypi/setuptools#unix-including-mac-os-x-curl Other: https://pypi.python.org/pypi/setuptools#installation-instructions """) sys.exit(1) # The C-compiled coverage engine is WAY faster (and less buggy) than the pure # python version, so we build the dist_egg if necessary. if not os.path.exists(cov_egg): import subprocess print 'Building Coverage 3.7.1' p = subprocess.Popen([sys.executable, 'setup.py', 'bdist_egg'], cwd=cov_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: print 'Error while building :(' print stdout print stderr if sys.platform.startswith('linux'): print textwrap.dedent(""" You probably don't have the 'python-dev' package installed. Install it by running: sudo apt-get install python-dev """) else: print textwrap.dedent(""" I'm not sure what's wrong, but your system seems incapable of building python extensions. Please fix that by installing a Python with headers and the approprite command-line build tools for your platform. """) sys.exit(1)
def update_event(self, inp=-1): self.set_output_val(0, sysconfig.get_python_version())
def read_callback(self, io, err, buf, auxdata): if self.to_compare: iolen = len(self.to_compare) elif self.to_waitfor: iolen = len(self.to_waitfor) else: iolen = None if (debug or self.debug) and iolen != None: print("%s: Got %d bytes at pos %d of %d" % (self.name, len(buf), self.compared, iolen)) if (debug >= 2 or self.debug >= 2): s = "" for i in range(0, len(buf)): if curses.ascii.isprint(buf[i]): if (sysconfig.get_python_version() >= "3.0"): s = s + str(buf[i:i + 1], "utf-8") else: s = s + str(buf[i:i + 1]) else: s = s + "\\x%2.2x" % i print("%s: Got data: (err %s %d bytes) %s" % (self.name, str(err), len(buf), s)) if (err): raise HandlerException(self.name + ": read: " + err) if (self.ignore_input): return len(buf) if (self.to_waitfor): for i in range(0, len(buf)): if buf[i] == self.to_waitfor[self.compared]: self.compared += 1 if (len(self.to_waitfor) == self.compared): self.to_waitfor = None io.read_cb_enable(False) self.waiter.wake() else: self.compared = 0 return len(buf) oob = False stream = 0 if auxdata: for i in auxdata: if i == "oob": oob = True elif i[0:7] == "stream=": stream = int(i[7:]) if self.stream and stream != self.stream: raise HandlerException( "%s: stream mismatch, expected %d, got %d " % (self.name, self.stream, stream)) if not self.stream and stream != 0: raise HandlerException("%s: not expecting stream, got %d " % (self.name, stream)) if oob: if not self.to_compare_oob: if (debug): print(self.name + ": Got oob data, but nothing to compare") io.read_cb_enable(False) return len(buf) compared = self.compared_oob compare_with = self.to_compare_oob oob = "oob " else: if not self.to_compare: if (debug): print(self.name + ": Got data, but nothing to compare") io.read_cb_enable(False) return len(buf) compared = self.compared compare_with = self.to_compare oob = "" if (len(buf) > len(compare_with)): count = len(compare_with) else: count = len(buf) if count > self.chunksize: count = self.chunksize for i in range(0, count): if (buf[i] != compare_with[compared]): raise HandlerException( "%s: %scompare failure on byte %d, " "expected %x, got %x" % (self.name, oob, compared, ord( compare_with[compared]), ord(buf[i]))) compared += 1 if oob == "oob ": self.compared_oob = compared if (self.compared_oob >= len(self.to_compare_oob)): self.to_compare_oob = None io.read_cb_enable(False) self.waiter.wake() else: self.compared = compared if (self.compared >= len(self.to_compare)): self.to_compare = None io.read_cb_enable(False) self.waiter.wake() return count
def generate(env): """Add Builders and construction variables to the Environment.""" if not 'boost_python' in env['TOOLS'][:-1]: env.Tool('system') env.Tool('textfile') PYTHON_VERSION = sysconfig.get_python_version() env.AppendUnique( LIBS=['boost_python' + PYTHON_VERSION.replace(".", "")]) env.AppendUnique( CPPDEFINES=['BOOST_PYTHON_DYNAMIC_LIB', 'BOOST_ALL_NO_LIB']) def BoostPythonExtension(env, target, sources, preserve_egg_dir=False): # Code to build "target" from "source" SYSTEM = env['SYSTEM'] parents = [] if not preserve_egg_dir: parent = os.path.dirname(env.File(target).srcnode().abspath) while os.path.exists(os.path.join(parent, '__init__.py')): parents.append(os.path.basename(parent)) parent = os.path.dirname(parent) if parents: target = os.path.join(os.path.join(*reversed(parents)), os.path.basename(target)) else: target = os.path.basename(target) if not SYSTEM == 'win': target += '.so' target = env.File(os.path.join('$SP_DIR', target)) else: target += '.pyd' target = env.File(target) else: if not SYSTEM == 'win': target += '.so' target = env.File(target).srcnode() else: target += '.pyd' target = env.File(target) targets = list( itertools.chain(*[ env.SharedObject(None, source) for source in sources if source.suffix in ['.cpp', '.cxx', '.c++'] ])) sources = [source for source in sources if source.suffix == '.h'] if len(sources) == 1 and not SYSTEM == 'win': env.AppendUnique(CCFLAGS=['-Winvalid-pch']) cmd = env.subst( '$CXX' ) + ' -o $TARGET -x c++-header -c -fPIC ' + env.subst( '$SHCXXFLAGS $CCFLAGS $_CCCOMCOM').replace('-x c++', '') + ' $SOURCE' cmd = env.Command(sources[0].target_from_source('', '.h.gch'), sources[0], cmd) env.Depends(targets, cmd) if SYSTEM == 'osx': env['CXX'] += " -include " + sources[0].target_from_source( '', '.h').abspath env.Depends(target, targets) if SYSTEM == 'win': response_file = os.path.abspath('response_file.rsp') with open(response_file, 'w') as filehandler: filehandler.write(" ".join( [tgt.abspath.replace('/', '\\') for tgt in targets])) env.Append(LINKFLAGS='@"' + response_file + '"') else: response = env.Textfile( 'response_file.rsp', [tgt.abspath.replace('\\', '/') for tgt in targets], LINESEPARATOR=" ") env.Append(LINKFLAGS='@' + response[0].abspath) env.Depends(target, response) if SYSTEM == 'win': pyd, lib, exp = env.SharedLibrary(target, [], SHLIBPREFIX='', SHLIBSUFFIX='.pyd') if preserve_egg_dir: return env.Install( os.path.dirname(target.srcnode().abspath), pyd) else: return env.Install( os.path.join('$SP_DIR', Path(target).parent), pyd) elif SYSTEM == 'osx': return env.LoadableModule( target, [], SHLIBPREFIX='', SHLINKFLAGS='$LINKFLAGS -bundle', FRAMEWORKSFLAGS='-flat_namespace -undefined suppress') else: return env.LoadableModule(target, [], SHLIBPREFIX='') env.AddMethod(BoostPythonExtension) env.Tool('python')
def language_version(self, state, args, kwargs): return sysconfig.get_python_version()
def install( self, install_options, # type: List[str] global_options=None, # type: Optional[Sequence[str]] root=None, # type: Optional[str] home=None, # type: Optional[str] prefix=None, # type: Optional[str] warn_script_location=True, # type: bool use_user_site=False, # type: bool pycompile=True # type: bool ): # type: (...) -> None global_options = global_options if global_options is not None else [] if self.editable: self.install_editable( install_options, global_options, prefix=prefix, ) return if self.is_wheel: version = wheel.wheel_version(self.source_dir) wheel.check_compatibility(version, self.name) scheme = distutils_scheme( self.name, user=use_user_site, home=home, root=root, isolated=self.isolated, prefix=prefix, ) self.move_wheel_files( self.source_dir, scheme=scheme, warn_script_location=warn_script_location, pycompile=pycompile, ) self.install_succeeded = True return # Extend the list of global and install options passed on to # the setup.py call with the ones from the requirements file. # Options specified in requirements file override those # specified on the command line, since the last option given # to setup.py is the one that is used. global_options = list(global_options) + \ self.options.get('global_options', []) install_options = list(install_options) + \ self.options.get('install_options', []) header_dir = None # type: Optional[str] if running_under_virtualenv(): py_ver_str = 'python' + sysconfig.get_python_version() header_dir = os.path.join( sys.prefix, 'include', 'site', py_ver_str, self.name ) with TempDirectory(kind="record") as temp_dir: record_filename = os.path.join(temp_dir.path, 'install-record.txt') install_args = make_setuptools_install_args( self.setup_py_path, global_options=global_options, install_options=install_options, record_filename=record_filename, root=root, prefix=prefix, header_dir=header_dir, no_user_config=self.isolated, pycompile=pycompile, ) runner = runner_with_spinner_message( "Running setup.py install for {}".format(self.name) ) with indent_log(), self.build_env: runner( cmd=install_args, cwd=self.unpacked_source_directory, ) if not os.path.exists(record_filename): logger.debug('Record file %s not found', record_filename) return self.install_succeeded = True def prepend_root(path): # type: (str) -> str if root is None or not os.path.isabs(path): return path else: return change_root(root, path) with open(record_filename) as f: for line in f: directory = os.path.dirname(line) if directory.endswith('.egg-info'): egg_info_dir = prepend_root(directory) break else: logger.warning( 'Could not find .egg-info directory in install record' ' for %s', self, ) # FIXME: put the record somewhere return new_lines = [] with open(record_filename) as f: for line in f: filename = line.strip() if os.path.isdir(filename): filename += os.path.sep new_lines.append( os.path.relpath(prepend_root(filename), egg_info_dir) ) new_lines.sort() ensure_dir(egg_info_dir) inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt') with open(inst_files_path, 'w') as f: f.write('\n'.join(new_lines) + '\n')
# # build the opening book # import os import sysconfig import sys build_lib = "lib.%s-%s" % (sysconfig.get_platform(), sysconfig.get_python_version()) pypath = os.path.join("build", build_lib, "gshogi") sys.path.append(pypath) import engine text_opening_book = "data/gnushogi.tbk" bin_opening_book = "gshogi/data/opening.bbk" booksize = 8000 bookmaxply = 40 # check input file exists if (not os.path.exists(text_opening_book)): print("Input file", text_opening_book, "not found") sys.exit() # create data folder for bin book data_folder = os.path.dirname(bin_opening_book) if not os.path.exists(data_folder): try: os.makedirs(data_folder) except OSError as exc:
#!/usr/bin/python # import sysconfig module #provide access to python's configuration information import sysconfig #returns an installation path corresponding to the path name print("Path Name : ", sysconfig.get_path("stdlib")) print() #returns a string that identifies the current platform print("Current Platform : ", sysconfig.get_platform()) print() # returns the MAJOR.MINOR Python version number as a string print("Python Version Number : ", sysconfig.get_python_version()) print() #returns a tuple containing all schemes print("Scheme Names : ", sysconfig.get_scheme_names()) print()
def run(self): # Generate metadata first self.run_command("egg_info") # We run install_lib before install_data, because some data hacks # pull their data path from the install_lib command. log.info("installing library code to %s", self.bdist_dir) instcmd = self.get_finalized_command('install') old_root = instcmd.root instcmd.root = None if self.distribution.has_c_libraries() and not self.skip_build: self.run_command('build_clib') cmd = self.call_command('install_lib', warn_dir=0) instcmd.root = old_root all_outputs, ext_outputs = self.get_ext_outputs() self.stubs = [] to_compile = [] for (p, ext_name) in enumerate(ext_outputs): filename, ext = os.path.splitext(ext_name) pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py') self.stubs.append(pyfile) log.info("creating stub loader for %s", ext_name) if not self.dry_run: write_stub(os.path.basename(ext_name), pyfile) to_compile.append(pyfile) ext_outputs[p] = ext_name.replace(os.sep, '/') if to_compile: cmd.byte_compile(to_compile) if self.distribution.data_files: self.do_install_data() # Make the EGG-INFO directory archive_root = self.bdist_dir egg_info = os.path.join(archive_root, 'EGG-INFO') self.mkpath(egg_info) if self.distribution.scripts: script_dir = os.path.join(egg_info, 'scripts') log.info("installing scripts to %s", script_dir) self.call_command('install_scripts', install_dir=script_dir, no_ep=1) self.copy_metadata_to(egg_info) native_libs = os.path.join(egg_info, "native_libs.txt") if all_outputs: log.info("writing %s", native_libs) if not self.dry_run: ensure_directory(native_libs) libs_file = open(native_libs, 'wt') libs_file.write('\n'.join(all_outputs)) libs_file.write('\n') libs_file.close() elif os.path.isfile(native_libs): log.info("removing %s", native_libs) if not self.dry_run: os.unlink(native_libs) write_safety_flag(os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()) if os.path.exists(os.path.join(self.egg_info, 'depends.txt')): log.warn( "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n" "Use the install_requires/extras_require setup() args instead." ) if self.exclude_source_files: self.zap_pyfiles() # Make the archive make_zipfile(self.egg_output, archive_root, verbose=self.verbose, dry_run=self.dry_run, mode=self.gen_header()) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) # Add to 'Distribution.dist_files' so that the "upload" command works getattr(self.distribution, 'dist_files', []).append( ('bdist_egg', get_python_version(), self.egg_output))
def log_startup_info(): global _pre_log_buffer if len(_pre_log_buffer) > 0: _log.info('early startup log buffer:') for line in _pre_log_buffer: _log.info(' ' + line) del _pre_log_buffer _log.info('GNUmed client version [%s] on branch [%s]', current_client_version, current_client_branch) _log.info('Platform: %s', platform.uname()) _log.info(('Python %s on %s (%s)' % (sys.version, sys.platform, os.name)).replace('\n', '<\\n>')) try: import lsb_release _log.info('lsb_release: %s', lsb_release.get_distro_information()) except ImportError: pass _log.info('module <sys> info:') attrs2skip = ['__doc__', 'copyright', '__name__', '__spec__'] for attr_name in dir(sys): if attr_name in attrs2skip: continue if attr_name.startswith('set'): continue attr = getattr(sys, attr_name) if not attr_name.startswith('get'): _log.info('%s: %s', attr_name.rjust(30), attr) continue if callable(attr): try: _log.info('%s: %s', attr_name.rjust(30), attr()) except Exception: _log.exception('%s: <cannot log>', attr_name.rjust(30)) continue _log.info('module <platform> info:') attrs2skip = [ '__doc__', '__copyright__', '__name__', '__spec__', '__cached__', '__builtins__' ] for attr_name in dir(platform): if attr_name in attrs2skip: continue if attr_name.startswith('set'): continue attr = getattr(platform, attr_name) if callable(attr): if attr_name.startswith('_'): _log.info('%s: %s', attr_name.rjust(30), attr) continue try: _log.info('%s: %s', attr_name.rjust(30), attr()) except Exception: _log.exception('%s: <cannot log>', attr_name.rjust(30)) continue _log.info('%s: %s', attr_name.rjust(30), attr) continue _log.info('module <os> info:') for n in os.confstr_names: _log.info('%s: %s', ('confstr[%s]' % n).rjust(40), os.confstr(n)) for n in os.sysconf_names: try: _log.info('%s: %s', ('sysconf[%s]' % n).rjust(40), os.sysconf(n)) except Exception: _log.exception('%s: <invalid> ??', ('sysconf[%s]' % n).rjust(30)) os_attrs = [ 'name', 'ctermid', 'getcwd', 'get_exec_path', 'getegid', 'geteuid', 'getgid', 'getgroups', 'getlogin', 'getpgrp', 'getpid', 'getppid', 'getresuid', 'getresgid', 'getuid', 'supports_bytes_environ', 'uname', 'get_terminal_size', 'pathconf_names', 'times', 'cpu_count', 'curdir', 'pardir', 'sep', 'altsep', 'extsep', 'pathsep', 'defpath', 'linesep', 'devnull' ] for attr_name in os_attrs: attr = getattr(os, attr_name) if callable(attr): try: _log.info('%s: %s', attr_name.rjust(40), attr()) except Exception as exc: _log.error('%s: a callable, but call failed (%s)', attr_name.rjust(40), exc) continue _log.info('%s: %s', attr_name.rjust(40), attr) _log.info('process environment:') for key, val in os.environ.items(): _log.info(' %s: %s' % (('${%s}' % key).rjust(40), val)) import sysconfig _log.info('module <sysconfig> info:') _log.info(' platform [%s] -- python version [%s]', sysconfig.get_platform(), sysconfig.get_python_version()) _log.info(' sysconfig.get_paths():') paths = sysconfig.get_paths() for path in paths: _log.info('%s: %s', path.rjust(40), paths[path]) _log.info(' sysconfig.get_config_vars():') conf_vars = sysconfig.get_config_vars() for var in conf_vars: _log.info('%s: %s', var.rjust(45), conf_vars[var])