def test_no_home_directory(self): # bpo-10496: getuserbase() and getusersitepackages() must not fail if # the current user has no home directory (if expanduser() returns the # path unchanged). site.USER_SITE = None site.USER_BASE = None with EnvironmentVarGuard() as environ, \ mock.patch('os.path.expanduser', lambda path: path): del environ['PYTHONUSERBASE'] del environ['APPDATA'] user_base = site.getuserbase() self.assertTrue(user_base.startswith('~' + os.sep), user_base) user_site = site.getusersitepackages() self.assertTrue(user_site.startswith(user_base), user_site) with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \ mock.patch.object(site, 'addsitedir') as mock_addsitedir, \ support.swap_attr(site, 'ENABLE_USER_SITE', True): # addusersitepackages() must not add user_site to sys.path # if it is not an existing directory known_paths = set() site.addusersitepackages(known_paths) mock_isdir.assert_called_once_with(user_site) mock_addsitedir.assert_not_called() self.assertFalse(known_paths)
def create_sitecustomize(path): extra_sitepacks = [] sitepacks = ensure_list(site.getsitepackages()) user_sitepacks = ensure_list(site.getusersitepackages()) fp = open("bin/sitecustomize.py", "w") print >>fp, 'import os, site, sys' print >>fp, 'EXTRA_SITE_PACKAGES = ' + str(EXTRA_SITE_PACKAGES) print >>fp, 'SYSTEM_SITE_PACKAGES = ' + str(SYSTEM_SITE_PACKAGES) print >>fp, 'USER_SITE_PACKAGES = ' + str(USER_SITE_PACKAGES) if extra_sitepacks: print >>fp, 'extra_sitepacks = ["' + '", "'.join(extra_sitepacks) + '"]' else: print >>fp, 'extra_sitepacks = [ ]' if sitepacks: print >>fp, 'sitepacks = ["' + '", "'.join(sitepacks) + '"]' else: print >>fp, 'sitepacks = [ ]' if user_sitepacks: print >>fp, 'user_sitepacks = ["' + '", "'.join(user_sitepacks) + '"]' else: print >>fp, 'user_sitepacks = [ ]' print >>fp, site_script fp.close()
def _get_default_library_roots(cls): # Provide sensible defaults if not in env vars. import site roots = [sys.prefix] if hasattr(sys, 'base_prefix'): roots.append(sys.base_prefix) if hasattr(sys, 'real_prefix'): roots.append(sys.real_prefix) if hasattr(site, 'getusersitepackages'): site_paths = site.getusersitepackages() if isinstance(site_paths, (list, tuple)): for site_path in site_paths: roots.append(site_path) else: roots.append(site_paths) if hasattr(site, 'getsitepackages'): site_paths = site.getsitepackages() if isinstance(site_paths, (list, tuple)): for site_path in site_paths: roots.append(site_path) else: roots.append(site_paths) for path in sys.path: if os.path.exists(path) and os.path.basename(path) == 'site-packages': roots.append(path) return sorted(set(roots))
def check_installed(): "Check that we're installed, if not, install" s = site.getusersitepackages() # There should be a symlink sym = os.path.join( s, "sr" ) # to here: target = os.path.abspath( os.path.join( os.path.dirname(__file__), "..", "python" ) ) if not os.path.exists( s ): os.makedirs( s ) if os.path.exists(sym): try: cur_target = os.readlink( sym ) c = os.path.abspath( cur_target ) if c == target: "Installed, and pointing at the right place" return # Wrong target directory -- rewrite it os.unlink( sym ) except OSError: print >>sys.stderr, "Error: %s is not a symlink. Refusing to continue." % sym exit(1) print >>sys.stderr, "Installing SR python usersitepackage" os.symlink( target, sym )
def run(self): _install.run(self) if '--user' in sys.argv[-1] : userdir = site.getusersitepackages()+"/pyasp/bin" self.get_binaries(userdir) cmd="chmod +x "+userdir+"/*" print(cmd) os.system(cmd) else : py_version = "%s.%s" % (sys.version_info[0], sys.version_info[1]) paths = [] paths.append(sys.prefix+"/lib/python%s/dist-packages/pyasp/bin" % py_version) paths.append(sys.prefix+"/lib/python%s/site-packages/pyasp/bin" % py_version) paths.append(sys.prefix+"/local/lib/python%s/dist-packages/pyasp/bin" % py_version) paths.append(sys.prefix+"/local/lib/python%s/site-packages/pyasp/bin" % py_version) paths.append("/Library/Python/%s/site-packages/pyasp/bin" % py_version) cmd = None for path in paths: if os.path.exists(path): self.get_binaries(path) cmd = "chmod +x "+path+"/*" break if cmd: print(cmd) os.system(cmd) else: print("pyasp binaries path not found. You need to download and put in place the binaries for gringo3, gringo4 and clasp in order to start using pyasp.")
def getopts(argv): """returns command line options as tuple.""" user = False set_env = True version = WAF_VERSION tools = WAF_TOOLS bindir = BINDIR libdir = LIBDIR opts, args = getopt.getopt(argv[1:], "hv:t:us", ["help", "version=", "tools=", "user", "skip-env"]) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-v", "--version"): version = arg elif opt in ("-t", "--tools"): tools = arg elif opt in ("-u", "--user"): user = True elif opt in ("-s", "--skip-env"): set_env = False if user: # install in home directory but not on windows or virtualenv if sys.platform != "win32" and not hasattr(sys, "real_prefix"): bindir = "~/.local/bin" libdir = site.getusersitepackages() return (version, tools, bindir, libdir, set_env)
def pytest_report_header(config): print('PYDEVD_USE_CYTHON: %s' % (TEST_CYTHON,)) print('PYDEVD_TEST_JYTHON: %s' % (TEST_JYTHON,)) try: import multiprocessing except ImportError: pass else: print('Number of processors: %s' % (multiprocessing.cpu_count(),)) print('Relevant system paths:') print('sys.prefix: %s' % (sys.prefix,)) if hasattr(sys, 'base_prefix'): print('sys.base_prefix: %s' % (sys.base_prefix,)) if hasattr(sys, 'real_prefix'): print('sys.real_prefix: %s' % (sys.real_prefix,)) if hasattr(site, 'getusersitepackages'): print('site.getusersitepackages(): %s' % (site.getusersitepackages(),)) if hasattr(site, 'getsitepackages'): print('site.getsitepackages(): %s' % (site.getsitepackages(),)) for path in sys.path: if os.path.exists(path) and os.path.basename(path) == 'site-packages': print('Folder with "site-packages" in sys.path: %s' % (path,))
def list_site_packages_paths(): site_packages_paths = set([site.USER_SITE]) try: site_packages_paths.update(site.getsitepackages()) except AttributeError: pass try: user_site = site.getusersitepackages() if isinstance(user_site, str): site_packages_paths.add(user_site) else: site_packages_paths.update(user_site) except AttributeError: pass try: virtualenv_path = os.environ['VIRTUAL_ENV'] except KeyError: pass else: virtualenv_src_path = os.path.join(virtualenv_path, 'src') site_packages_paths.update( path for path in sys.path if path.startswith(virtualenv_path) and ( 'site-packages' in path or path.startswith(virtualenv_src_path) ) ) return site_packages_paths
def AddToPath(self, package): # Find all 'site-packages' directories. sp = getsitepackages() sp.append(getusersitepackages()) for path in sp: if path not in sys.path and os.path.exists(path): sys.path.append(path) # Add package to sys.path. def _AddToPath(name, version): for path in sp: packageFileName = name + '-' + version files = DirFileSet(path, [packageFileName + '*.egg', packageFileName + '*.zip'], withRootDirName = True) for fn in files: if fn not in sys.path and os.path.exists(fn): sys.path.append(fn) _AddToPath(package.artifactId, package.version) _AddToPath(package.artifactId.replace('-', '_'), package.version) # Try to add all the packages that are missing in # sys.path but are listed in: easy-install.pth. for path in sp: pth = os.path.join(path, 'easy-install.pth') try: pth = OS.LoadFile(pth) pth = pth.split('\n') for fn in pth: if not fn.startswith(('#', "import ", "import\t")): fn = os.path.realpath(os.path.join(path, fn)) if fn not in sys.path and os.path.exists(fn): sys.path.append(fn) except Exception as E: #self.Log(str(E), level = LogLevel.VERBOSE) pass
def binaries_directory(): """Return the installation directory, or None""" if '--user' in sys.argv: paths = (site.getusersitepackages(),) else: py_version = '%s.%s' % (sys.version_info[0], sys.version_info[1]) paths = (s % (py_version) for s in ( sys.prefix + '/lib/python%s/dist-packages/', sys.prefix + '/lib/python%s/site-packages/', sys.prefix + '/local/lib/python%s/dist-packages/', sys.prefix + '/local/lib/python%s/site-packages/', '/Library/Python/%s/site-packages/', )) # yield the first valid path for path in paths: # add the package and bin subdir and, if exists, return it path = os.path.join(path, '%s/%s' % (info.__pkg_name__, constant.REL_DIR_BIN)) if os.path.exists(path): return path logging.getLogger().error( 'pyasp binaries path not found. You need to download and' ' put in place the binaries for gringo3, gringo4 and clasp' ' in order to start using pyasp.' ' You can find binaries from ' + BINARIES_BASE_URL + ' or https://sourceforge.net/projects/potassco/files/,' ' or compile them yourself.' ) exit() return None
def getopts(argv): '''returns command line options as tuple.''' user = False set_env = True version = WAF_VERSION tools = WAF_TOOLS bindir = BINDIR libdir = LIBDIR opts, args = getopt.getopt(argv[1:], 'hv:t:us', ['help', 'version=', 'tools=', 'user', 'skip-env']) for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit() elif opt in ('-v', '--version'): version = arg elif opt in ('-t', '--tools'): tools = arg elif opt in ('-u', '--user'): user = True elif opt in ('-s', '--skip-env'): set_env = False if user: # install in home directory but not on windows or virtualenv if sys.platform != "win32" and not hasattr(sys, 'real_prefix'): bindir = "~/.local/bin" libdir = site.getusersitepackages() return (version, tools, bindir, libdir, set_env)
def __init__(self, verbose=True): self.plugin_types = ('wralea', 'plugin', 'adapters', 'interfaces') self.groups = set() self.managers = {} self._services = {} self._interfaces = {} self._lowername = {} # list all path supporting python modules paths = site.getsitepackages() usersite = site.getusersitepackages() if isinstance(usersite, basestring): paths.append(usersite) elif isinstance(usersite, (tuple, list)): paths += list(usersite) paths += sys.path # scan all entry_point and list different groups for path in set(paths): distribs = pkg_resources.find_distributions(path) for distrib in distribs : for group in distrib.get_entry_map(): self.groups.add(group) self.groups = [group for group in self.groups] self.tags = self._clean_lst(self.groups) self._load_interfaces()
def fixate(): "puts activation code to usercustomize.py for user" print_message('Fixate') import site userdir = site.getusersitepackages() if not userdir: raise PundleException('Can`t fixate due user have not site package directory') try: makedirs(userdir) except OSError: pass template = FIXATE_TEMPLATE.replace('op.dirname(__file__)', "'%s'" % op.abspath(op.dirname(__file__))) usercustomize_file = op.join(userdir, 'usercustomize.py') print_message('Will edit %s file' % usercustomize_file) if op.exists(usercustomize_file): content = open(usercustomize_file).read() if '# pundle user customization start' in content: regex = re.compile(r'\n# pundle user customization start.*# pundle user customization end\n', re.DOTALL) content, res = regex.subn(template, content) open(usercustomize_file, 'w').write(content) else: open(usercustomize_file, 'a').write(content) else: open(usercustomize_file, 'w').write(template) link_file = op.join(userdir, 'pundle.py') if op.lexists(link_file): print_message('Remove exist link to pundle') os.unlink(link_file) print_message('Create link to pundle %s' % link_file) os.symlink(op.abspath(__file__), link_file) print_message('Complete')
def test_getusersitepackages(self): site.USER_SITE = None site.USER_BASE = None user_site = site.getusersitepackages() # the call sets USER_BASE *and* USER_SITE self.assertEqual(site.USER_SITE, user_site) self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
def _user_site_packages(): if not _in_virtualenv(): return site.getusersitepackages() else: home = _find_user_home() major = sys.version_info.major minor = sys.version_info.minor path = '/.local/lib/python{major}.{minor}/site-packages'.format(major=major, minor=minor) return home+path
def main(): locations = [site.getusersitepackages()] locations.extend(site.getsitepackages()) for root in locations: if os.path.isdir(root): for name in os.listdir(root): if PKGNAME in name: abspath = os.path.join(root, name) rmpath(abspath)
def main(): qmakePath = getEnv("QMAKE", "qmake") sipPath = getEnv("SIP", "sip") sipConfig = sipconfig.Configuration() config = Config(qmakePath) projectPath = getEnv("PROJECT_PATH", "../..") libraryPath = getEnv("LIBRARY_PATH", projectPath + "/fakevim") sipFilePath = getEnv("SIP_FILE_PATH", projectPath + "/python/fakevim.sip") pyQtIncludePath = getEnv("PYQT_INCLUDE_PATH", "/usr/share/sip/PyQt" + (config.hasQt5() and "5" or "4")) commandOutput( sipPath, config.sipFlags().split(" ") + ["-I", pyQtIncludePath, "-b", "fakevim_python.pro", "-o", "-c", ".", sipFilePath], ) with open("fakevim_python.pro", "a") as pro: pro.write( """ TEMPLATE = lib CONFIG += release plugin no_plugin_name_prefix QT += widgets TARGET = $$target HEADERS = $$headers "{projectPythonInclude}/fakevimproxy.h" SOURCES = $$sources "{projectPythonInclude}/fakevimproxy.cpp" INCLUDEPATH += "{sipInclude}" "{pythonInclude}" "{projectInclude}" "{projectPythonInclude}" LIBS += -Wl,-rpath,"{libraryPath}" -L"{libraryPath}" -lfakevim "{pythonLibrary}" DEFINES += FAKEVIM_PYQT_MAJOR_VERSION={qtVersion} isEmpty(PREFIX) {{ PREFIX = "{installPath}" }} target.path = $$PREFIX INSTALLS += target """.format( pythonInclude=sysconfig.get_python_inc(), sipInclude=sipConfig.sip_inc_dir, projectInclude=projectPath, projectPythonInclude=projectPath + "/python", libraryPath=libraryPath, pythonLibrary=sysconfig.get_config_var("LIBDIR") + "/" + sysconfig.get_config_var("MULTIARCH") + "/" + sysconfig.get_config_var("LDLIBRARY"), qtVersion=config.hasQt5() and 5 or 4, installPath=site.getusersitepackages(), ).replace( "\n ", "\n" ) )
def main(): qmakePath = getEnv('QMAKE', 'qmake') sipPath = getEnv('SIP', 'sip') sipConfig = sipconfig.Configuration() config = Config(qmakePath) projectPath = getEnv('PROJECT_PATH', os.getcwd() + '/..') libraryPath = getEnv('LIBRARY_PATH', projectPath + '/fakevim') sipFilePath = getEnv('SIP_FILE_PATH', projectPath + '/python/fakevim.sip') pyQtIncludePath = getEnv('PYQT_INCLUDE_PATH', '/usr/share/sip/PyQt' + (config.hasQt5() and '5' or '4')) commandOutput(sipPath, config.sipFlags().split(' ') + [ '-I', pyQtIncludePath, '-b', 'fakevim_python.pro', '-o', '-c', '.', sipFilePath ]) with open('fakevim_python.pro', 'a') as pro: pro.write( ''' TEMPLATE = lib CONFIG += release plugin no_plugin_name_prefix QT += widgets TARGET = $$target HEADERS = $$headers "{projectPythonInclude}/fakevimproxy.h" SOURCES = $$sources "{projectPythonInclude}/fakevimproxy.cpp" INCLUDEPATH += "{sipInclude}" "{pythonInclude}" "{projectInclude}" "{projectPythonInclude}" LIBS += -Wl,-rpath,"{libraryPath}" -L"{libraryPath}" -lfakevim "{pythonLibrary}" DEFINES += FAKEVIM_PYQT_MAJOR_VERSION={qtVersion} isEmpty(PREFIX) {{ PREFIX = "{installPath}" }} target.path = $$PREFIX INSTALLS += target '''.format( pythonInclude = sysconfig.get_python_inc(), sipInclude = sipConfig.sip_inc_dir, projectInclude = projectPath, projectPythonInclude = projectPath + "/python", libraryPath = libraryPath, pythonLibrary = sysconfig.get_config_var('LIBDIR') + "/" + sysconfig.get_config_var('MULTIARCH') + "/" + sysconfig.get_config_var('LDLIBRARY'), qtVersion = config.hasQt5() and 5 or 4, installPath = site.getusersitepackages() ).replace('\n ', '\n') )
def python_env(options, unset_env=False): """ Setup our overrides_hack.py as sitecustomize.py script in user site-packages if unset_env=False, else unset, previously set env. """ subprojects_path = os.path.join(options.builddir, "subprojects") gst_python_path = os.path.join(SCRIPTDIR, "subprojects", "gst-python") if not os.path.exists(os.path.join(subprojects_path, "gst-python")) or \ not os.path.exists(gst_python_path): return False if in_venv (): sitepackages = get_python_lib() else: sitepackages = site.getusersitepackages() if not sitepackages: return False sitecustomize = os.path.join(sitepackages, "sitecustomize.py") overrides_hack = os.path.join(gst_python_path, "testsuite", "overrides_hack.py") mesonconfig = os.path.join(gst_python_path, "testsuite", "mesonconfig.py") mesonconfig_link = os.path.join(sitepackages, "mesonconfig.py") if not unset_env: if os.path.exists(sitecustomize): if os.path.realpath(sitecustomize) == overrides_hack: print("Customize user site script already linked to the GStreamer one") return False old_sitecustomize = os.path.join(sitepackages, "old.sitecustomize.gstuninstalled.py") shutil.move(sitecustomize, old_sitecustomize) elif not os.path.exists(sitepackages): os.makedirs(sitepackages) os.symlink(overrides_hack, sitecustomize) os.symlink(mesonconfig, mesonconfig_link) return os.path.realpath(sitecustomize) == overrides_hack else: if not os.path.realpath(sitecustomize) == overrides_hack: return False os.remove(sitecustomize) os.remove (mesonconfig_link) old_sitecustomize = os.path.join(sitepackages, "old.sitecustomize.gstuninstalled.py") if os.path.exists(old_sitecustomize): shutil.move(old_sitecustomize, sitecustomize) return True
def search_cheat (self): available = [] import site site_system = site.getsitepackages() site_user = site.getusersitepackages() for name in [site_user] + site_system: path = os.path.join(name, 'cheat') if not os.path.exists(path): continue path = os.path.join(path, 'cheatsheets') if not os.path.exists(path): continue available.append(path) return available
def _FindInPath(name, package): packageRegExp = re.compile(name + r'-([a-zA-Z0-9\._]+)-') for path in sys.path: m = packageRegExp.search(path) if m: return PackageId.FromPackage(package, version = m.group(1)) sp = getsitepackages() sp.append(getusersitepackages()) for path in sp: for fn in DirFileSet(path, packageRegExp, useRegExp = True): m = packageRegExp.search(fn) if m: return PackageId.FromPackage(package, version = m.group(1))
def get_kaizen_pth_path(self): if self._kaizen_pth is None: import site k_site = None for c_site in site.PREFIXES: if os.access(c_site, os.W_OK): k_site = c_site break if not k_site: if hasattr(site, "getusersitepackages"): k_site = site.getusersitepackages() else: k_site = site.USER_SITE self._kaizen_pth = os.path.join(k_site, "kaizen-rules.pth") return self._kaizen_pth
def register(linter): if not hasattr(linter, '_old_is_standard_module'): linter._old_is_standard_module = modutils.is_standard_module new_is_standard_module = partial(is_standard_module, linter) modutils.is_standard_module = new_is_standard_module imports.is_standard_module = new_is_standard_module # Add the user site packages to external import locations, if it exists try: for checker in linter._checkers['imports']: checker._site_packages.update(site.getsitepackages()) checker._site_packages.add(site.getusersitepackages()) except AttributeError: # Running in a virtual environment, in which case there is no # `site.getusersitepackages()` method. pass
def user_install(): sdir = site.getusersitepackages() # site directory idir = os.path.join( sdir, 'kmeans' ) # install directory cdir = os.path.dirname( os.path.realpath(__file__) ) # code directory if idir == cdir: raise Exception, 'Cannot install from the target directory.' if os.path.exists( idir ): reply = raw_input('Overwrite ' + idir + ' (y/n)?') if reply in ['y', 'Y', 'yes', 'Yes']: shutil.rmtree( idir ) else: return os.mkdir( idir ) for n in ['cykmeans.pyx', '__init__.py', 'kmeans.py', 'LICENSE', 'README.md', 'setup.py', 'test.py']: path = os.path.join( cdir, n ) shutil.copy( path, idir )
def main(args): import optparse parser = optparse.OptionParser() parser.usage = __doc__ parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() if len(args) < 0: parser.error("Not enough arguments given") usdir = site.getusersitepackages() if not os.path.exists(usdir): os.makedirs(usdir) ez_setup(usdir) return 0
def iter_groups(): groups = set() paths = site.getsitepackages() usersite = site.getusersitepackages() if isinstance(usersite, basestring): paths.append(usersite) elif isinstance(usersite, (tuple, list)): paths += list(usersite) paths += sys.path # scan all entry_point and list different groups for path in set(paths): distribs = pkg_resources.find_distributions(path) for distrib in distribs : for group in distrib.get_entry_map(): groups.add(group) for group in groups: yield group
def import_try_install(package, extern_url=None): """Try import the specified package. If the package not installed, try use pip to install and import if success. Parameters ---------- package : str The name of the package trying to import. extern_url : str or None, optional The external url if package is not hosted on PyPI. For example, you can install a package using: "pip install git+http://github.com/user/repo/tarball/master/egginfo=xxx". In this case, you can pass the url to the extern_url. Returns ------- <class 'Module'> The imported python module. """ try: return __import__(package) except ImportError: try: from pip import main as pipmain except ImportError: from pip._internal import main as pipmain # trying to install package url = package if extern_url is None else extern_url pipmain(['install', '--user', url]) # will raise SystemExit Error if fails # trying to load again try: return __import__(package) except ImportError: import sys import site user_site = site.getusersitepackages() if user_site not in sys.path: sys.path.append(user_site) return __import__(package) return __import__(package)
def list_site_packages_paths(): site_packages_paths = {site.USER_SITE} try: site_packages_paths.update(site.getsitepackages()) except AttributeError: pass try: site_packages_paths.update(site.getusersitepackages()) except AttributeError: pass try: virtualenv_path = os.environ['VIRTUAL_ENV'] except KeyError: pass else: site_packages_paths.update( path for path in sys.path if path.startswith(virtualenv_path) and 'site-packages' in path ) return site_packages_paths
def development_deploy(paths, dependencies=False, scripts=False, inject_setuptools=False): """Python packages deployment in development mode.""" items = list(paths) if isinstance(paths, (list, tuple, set)) else [paths] if items: original_path = os.getcwd() user_base_path = getuserbase() user_sites_path = getusersitepackages() user_bin_path = os.path.join(user_base_path, 'bin') for path in items: os.chdir(os.path.dirname(path)) # Making arguments arguments = [path, 'develop'] arguments.extend(['--install-dir', user_sites_path]) arguments.extend(['--script-dir', user_bin_path]) if not dependencies: arguments.append('--no-deps') if not scripts: arguments.append('--exclude-scripts') # Processing if not inject_setuptools: subprocess.Popen([sys.executable] + arguments).wait() else: handler = open(path, 'rb') content = handler.read() handler.close() # Adding setuptools import content = "import setuptools\n" + content # Updating arguments, path and executing sys.path.insert(0, '.') sys.argv = arguments exec(content, {'__file__': path}) sys.path[:] = sys.path[1:] # Go back to original path os.chdir(original_path)
def TestCustomizationModules(): print site.getusersitepackages()
def Test_2(): import site print site.getusersitepackages()
import site import os names = site.getusersitepackages() found = False for name in names: if (not found): fullname = name + os.sep + 'numpy' + os.sep + 'core' + os.sep + 'include' found = os.path.isdir(fullname) if (found): print(fullname) if (not found): names = site.getsitepackages() for name in names: if (not found): fullname = name + os.sep + 'numpy' + os.sep + 'core' + os.sep + 'include' found = os.path.isdir(fullname) if (found): print(fullname) if (not found): print('NOTFOUND')
def cmake_set_cache(name, value, ctype, doc): print('set({0} "{1}" CACHE {2} "{3}")'.format(name, value, ctype, doc)) def cmake_set(name, value): print('set({0} "{1}")'.format(name, value)) # print all NumPy include directories ds = numpy.distutils.misc_util.get_numpy_include_dirs() cmake_set_cache('NUMPY_INCLUDES', cmake_list(ds), 'STRING', 'NumPy include directores') cmake_set_cache('NUMPY_FOUND', 'ON', 'BOOL', 'NumPy found') cmake_set_cache('PYTHON_INCLUDE_DIRS', sc.get_python_inc(), 'STRING', 'Python includes') python_lib = os.path.join(sc.get_config_var('LIBDIR'), sc.get_config_var('LDLIBRARY')) cmake_set_cache('PYTHON_LIB', python_lib, 'FILEPATH', 'Python libarary') cmake_set_cache('PYTHON_VERSION', sc.get_config_var('VERSION'), 'STRING', 'Python Version') cmake_set('PYTHON_GLOBAL_INSTALL_DIR', sc.get_python_lib(plat_specific=True)) cmake_set('PYTHON_USER_INSTALL_DIR', site.getusersitepackages())
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = { '<frozen importlib._bootstrap>', '<frozen importlib._bootstrap_external>', sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), os.path.dirname(collections.__file__), } for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
# Add our py/ module directory so we can find our own libraries current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, 'py')) from rspy import log, file, repo, libci # Python's default list of paths to look for modules includes user-intalled. We want # to avoid those to take only the pyrealsense2 we actually compiled! # # Rather than rebuilding the whole sys.path, we instead remove: from site import getusersitepackages # not the other stuff, like quit(), exit(), etc.! #log.d( 'site packages=', getusersitepackages() ) #log.d( 'sys.path=', sys.path ) #log.d( 'removing', [p for p in sys.path if file.is_inside( p, getusersitepackages() )]) sys.path = [ p for p in sys.path if not file.is_inside(p, getusersitepackages()) ] #log.d( 'modified=', sys.path ) def usage(): ourname = os.path.basename(sys.argv[0]) print('Syntax: ' + ourname + ' [options] [dir]') print(' dir: location of executable tests to run') print('Options:') print( ' --debug Turn on debugging information (does not include LibRS debug logs; see --rslog)' ) print(' -v, --verbose Errors will dump the log to stdout') print( ' -q, --quiet Suppress output; rely on exit status (0=no failures)'
def main(argv): parser = argparse.ArgumentParser( description="The simple Python package installer for GraalVM") subparsers = parser.add_subparsers( title="Commands", dest="command", metavar="Use COMMAND --help for further help.") subparsers.add_parser("list", help="list locally installed packages") install_parser = subparsers.add_parser( "install", help="install a known package", description="Install a known package. Known packages are " + ", ".join(KNOWN_PACKAGES.keys())) install_parser.add_argument("package", help="comma-separated list") install_parser.add_argument("--prefix", help="user-site path prefix") subparsers.add_parser( "uninstall", help="remove installation folder of a local package", ).add_argument("package", help="comma-separated list") subparsers.add_parser( "pypi", help= "attempt to install a package from PyPI (untested, likely won't work, and it won't install dependencies for you)", description="Attempt to install a package from PyPI" ).add_argument( "package", help= "comma-separated list, can use `==` at the end of a package name to specify an exact version" ) args = parser.parse_args(argv) if args.command == "list": if site.ENABLE_USER_SITE: user_site = site.getusersitepackages() else: for s in site.getsitepackages(): if s.endswith("site-packages"): user_site = s break info("Installed packages:") for p in sys.path: if p.startswith(user_site): info(p[len(user_site) + 1:]) elif args.command == "uninstall": warn( "WARNING: I will only delete the package folder, proper uninstallation is not supported at this time." ) user_site = site.getusersitepackages() for pkg in args.package.split(","): deleted = False for p in sys.path: if p.startswith(user_site): # +1 due to the path separator pkg_name = p[len(user_site) + 1:] if pkg_name.startswith(pkg): if os.path.isdir(p): shutil.rmtree(p) else: os.unlink(p) deleted = True break if deleted: info("Deleted {}", p) else: xit("Unknown package: '%s'" % pkg) elif args.command == "install": for pkg in args.package.split(","): if pkg not in KNOWN_PACKAGES: xit("Unknown package: '%s'" % pkg) else: if args.prefix: KNOWN_PACKAGES[pkg](extra_opts=["--prefix", args.prefix]) else: KNOWN_PACKAGES[pkg]() elif args.command == "pypi": for pkg in args.package.split(","): install_from_pypi(pkg, ignore_errors=False)
if hasattr(sys, 'real_prefix'): # Within virtualenv. site_location.append( os.path.join( sys.prefix, "lib/python{}.{}/site-packages".format(py_version[0], py_version[1]))) site_location.append( os.path.join( sys.real_prefix, "lib/python{}.{}/site-packages".format(py_version[0], py_version[1]))) else: # System wide python. site_location += site.getsitepackages() site_location.append(site.getusersitepackages()) site_locations = [] for install_path in install_pathes: for loc in site_location: site_locations.append(os.path.join(loc, "{}/lib".format(install_path))) site_locations.append( os.path.join(loc, "{}/third_party/lib".format(install_path))) site_locations.append(os.path.join(package_dir, "lib")) site_locations.append(os.path.join(package_dir, "third_party/lib")) if platform.system() == "Linux": site_locations.append("$ORIGIN") site_locations.append("$ORIGIN/../third_party/lib")
def _user_site_packages(): return Path(site.getusersitepackages())
def bootstrap(topsrcdir): # Ensure we are running Python 2.7 or 3.5+. We put this check here so we # generate a user-friendly error message rather than a cryptic stack trace # on module import. major = sys.version_info[:2][0] if sys.version_info < (3, 6): print("Python 3.6+ is required to run mach.") print("You are running Python", platform.python_version()) sys.exit(1) # This directory was deleted in bug 1666345, but there may be some ignored # files here. We can safely just delete it for the user so they don't have # to clean the repo themselves. deleted_dir = os.path.join(topsrcdir, "third_party", "python", "psutil") if os.path.exists(deleted_dir): shutil.rmtree(deleted_dir, ignore_errors=True) if major == 3 and sys.prefix == sys.base_prefix: # We are not in a virtualenv. Remove global site packages # from sys.path. # Note that we don't ever invoke mach from a Python 2 virtualenv, # and "sys.base_prefix" doesn't exist before Python 3.3, so we # guard with the "major == 3" check. site_paths = set(site.getsitepackages() + [site.getusersitepackages()]) sys.path = [path for path in sys.path if path not in site_paths] # Global build system and mach state is stored in a central directory. By # default, this is ~/.mozbuild. However, it can be defined via an # environment variable. We detect first run (by lack of this directory # existing) and notify the user that it will be created. The logic for # creation is much simpler for the "advanced" environment variable use # case. For default behavior, we educate users and give them an opportunity # to react. We always exit after creating the directory because users don't # like surprises. sys.path[0:0] = mach_sys_path(topsrcdir) import mach.base import mach.main from mach.util import setenv from mozboot.util import get_state_dir # Set a reasonable limit to the number of open files. # # Some linux systems set `ulimit -n` to a very high number, which works # well for systems that run servers, but this setting causes performance # problems when programs close file descriptors before forking, like # Python's `subprocess.Popen(..., close_fds=True)` (close_fds=True is the # default in Python 3), or Rust's stdlib. In some cases, Firefox does the # same thing when spawning processes. We would prefer to lower this limit # to avoid such performance problems; processes spawned by `mach` will # inherit the limit set here. # # The Firefox build defaults the soft limit to 1024, except for builds that # do LTO, where the soft limit is 8192. We're going to default to the # latter, since people do occasionally do LTO builds on their local # machines, and requiring them to discover another magical setting after # setting up an LTO build in the first place doesn't seem good. # # This code mimics the code in taskcluster/scripts/run-task. try: import resource # Keep the hard limit the same, though, allowing processes to change # their soft limit if they need to (Firefox does, for instance). (soft, hard) = resource.getrlimit(resource.RLIMIT_NOFILE) # Permit people to override our default limit if necessary via # MOZ_LIMIT_NOFILE, which is the same variable `run-task` uses. limit = os.environ.get("MOZ_LIMIT_NOFILE") if limit: limit = int(limit) else: # If no explicit limit is given, use our default if it's less than # the current soft limit. For instance, the default on macOS is # 256, so we'd pick that rather than our default. limit = min(soft, 8192) # Now apply the limit, if it's different from the original one. if limit != soft: resource.setrlimit(resource.RLIMIT_NOFILE, (limit, hard)) except ImportError: # The resource module is UNIX only. pass from mozbuild.util import patch_main patch_main() def resolve_repository(): import mozversioncontrol try: # This API doesn't respect the vcs binary choices from configure. # If we ever need to use the VCS binary here, consider something # more robust. return mozversioncontrol.get_repository_object(path=topsrcdir) except (mozversioncontrol.InvalidRepoPath, mozversioncontrol.MissingVCSTool): return None def pre_dispatch_handler(context, handler, args): # If --disable-tests flag was enabled in the mozconfig used to compile # the build, tests will be disabled. Instead of trying to run # nonexistent tests then reporting a failure, this will prevent mach # from progressing beyond this point. if handler.category == "testing" and not handler.ok_if_tests_disabled: from mozbuild.base import BuildEnvironmentNotFoundException try: from mozbuild.base import MozbuildObject # all environments should have an instance of build object. build = MozbuildObject.from_environment() if build is not None and hasattr(build, "mozconfig"): ac_options = build.mozconfig["configure_args"] if ac_options and "--disable-tests" in ac_options: print( "Tests have been disabled by mozconfig with the flag " + '"ac_add_options --disable-tests".\n' + "Remove the flag, and re-compile to enable tests.") sys.exit(1) except BuildEnvironmentNotFoundException: # likely automation environment, so do nothing. pass def post_dispatch_handler(context, handler, instance, success, start_time, end_time, depth, args): """Perform global operations after command dispatch. For now, we will use this to handle build system telemetry. """ # Don't finalize telemetry data if this mach command was invoked as part of # another mach command. if depth != 1: return _finalize_telemetry_glean(context.telemetry, handler.name == "bootstrap", success) def populate_context(key=None): if key is None: return if key == "state_dir": state_dir = get_state_dir() if state_dir == os.environ.get("MOZBUILD_STATE_PATH"): if not os.path.exists(state_dir): print( "Creating global state directory from environment variable: %s" % state_dir) os.makedirs(state_dir, mode=0o770) else: if not os.path.exists(state_dir): if not os.environ.get("MOZ_AUTOMATION"): print(STATE_DIR_FIRST_RUN.format(userdir=state_dir)) try: sys.stdin.readline() except KeyboardInterrupt: sys.exit(1) print("\nCreating default state directory: %s" % state_dir) os.makedirs(state_dir, mode=0o770) return state_dir if key == "local_state_dir": return get_state_dir(srcdir=True) if key == "topdir": return topsrcdir if key == "pre_dispatch_handler": return pre_dispatch_handler if key == "post_dispatch_handler": return post_dispatch_handler if key == "repository": return resolve_repository() raise AttributeError(key) # Note which process is top-level so that recursive mach invocations can avoid writing # telemetry data. if "MACH_MAIN_PID" not in os.environ: setenv("MACH_MAIN_PID", str(os.getpid())) driver = mach.main.Mach(os.getcwd()) driver.populate_context_handler = populate_context if not driver.settings_paths: # default global machrc location driver.settings_paths.append(get_state_dir()) # always load local repository configuration driver.settings_paths.append(topsrcdir) for category, meta in CATEGORIES.items(): driver.define_category(category, meta["short"], meta["long"], meta["priority"]) # Sparse checkouts may not have all mach_commands.py files. Ignore # errors from missing files. Same for spidermonkey tarballs. repo = resolve_repository() missing_ok = (repo is not None and repo.sparse_checkout_present()) or os.path.exists( os.path.join(topsrcdir, "INSTALL")) for path in MACH_MODULES: try: driver.load_commands_from_file(os.path.join(topsrcdir, path)) except mach.base.MissingFileError: if not missing_ok: raise return driver
import os from glob import glob from distutils.core import setup from site import getusersitepackages resource_dir = getusersitepackages() def find_packages(): def convert(x): x = x.replace('/__init__.py', '') x = x.replace('/', '.') return x raw_pkgs = glob('**/__init__.py', recursive=True) processed_pkgs = list(map(convert, raw_pkgs)) return processed_pkgs def find_data_files(ext): target = "**/*.%s" % ext file_list = glob(target, recursive=True) dir_list = list(map(lambda x: os.path.split(x)[0], file_list)) dir_file_dict = {} for d, f in zip(dir_list, file_list): if d in dir_file_dict.keys(): dir_file_dict[d].append(f) else: dir_file_dict[d] = [f]
def getUserLevelSitePackagePath(self): """ Getting user level site package """ userLevelSitePackagePyhtonPath = "PYTHONPATH=" + site.getusersitepackages() + "/" return userLevelSitePackagePyhtonPath
def get_user_target_path(): '''Get the target path for user installation :return: target path ''' return os.path.join(site.getusersitepackages(), 'pycompss')
from __future__ import print_function import os, site #package = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'packages') package = os.path.dirname(os.path.abspath(__file__)) print(package) pathspec = r""" # Generated by Cord's installer (install_locally.py) # In the lines below, list the paths where Python should look for # supplied modules, one directory per line. # # If a directory does not exist when Python is started, it will be ignored. %s """ % package print("Adding path:", package) usp = site.getusersitepackages() if not os.path.exists(usp): os.makedirs(usp) uspfile = os.path.join(usp, 'cord.pth') open(uspfile, 'w').write(pathspec) print('Wrote to ' + uspfile) print("Cord package installed successfully!")
# Extract all of the Python packages for OpenMOC # (ie, openmoc.log, openmoc.materialize, etc) packages = config.packages, # Include SWIG interface files in package - this is important for PyPI package_data = {'' : ['*.i*']}, # Inject our custom compiler and linker triggers cmdclass={ 'build_ext': custom_build_ext, 'install': custom_install} ) # Rerun the build_py to setup links for C++ extension modules created by SWIG # This prevents us from having to install twice build_py = build_py(dist) build_py.ensure_finalized() build_py.run() # Remove the shared library in the site packages if "clean" in sys.argv: install_location = site.getsitepackages()[0] print("Removing build from " + install_location) os.system("rm -rf " + install_location + "/*openmoc*") install_location = site.getusersitepackages() print("Removing build from " + install_location) os.system("rm -rf " + install_location + "/*openmoc*") install_location = "./tests/" print("Removing build from " + install_location) os.system("rm -rf " + install_location + "openmoc " + install_location + "build")
help='custom binary install path') parser.add_argument('-s', dest='script_path', help='custom script install path') args = parser.parse_args() is_64bits = (args.target == 'win64') if (args.operation in ['install', 'upgrade', 'uninstall']) == ((args.package is None) or len(args.package) == 0): print( 'Package argument only required for install, upgrade and uninstall operations' ) exit(1) py_script_path = '.\\' if args.portable else site.getusersitepackages() + '\\' if args.script_path is not None: py_script_path = args.script_path if args.portable: plugin32_path = 'vapoursynth32\\plugins\\' plugin64_path = 'vapoursynth64\\plugins\\' elif is_sitepackage_install_portable(): import vapoursynth base_path = os.path.dirname(vapoursynth.__file__) plugin32_path = os.path.join(base_path, 'vapoursynth32', 'plugins') plugin64_path = os.path.join(base_path, 'vapoursynth64', 'plugins') del vapoursynth else: plugin32_path = os.path.join(os.getenv('APPDATA'), 'VapourSynth', 'plugins32')
#!/usr/bin/env python3 from distutils.core import setup import subprocess import os import site import sys if hasattr(site, 'getsitepackages'): pkg_dirs = site.getsitepackages() if site.getusersitepackages(): pkg_dirs.append(site.getusersitepackages()) for pkg_dir in pkg_dirs: srht_path = os.path.join(pkg_dir, "srht") if os.path.isdir(srht_path): break else: raise Exception("Can't find core srht module in your site packages " "directories. Please install it first.") else: srht_path = os.getenv("SRHT_PATH") if not srht_path: raise Exception("You're running inside a virtual environment. " "Due to virtualenv limitations, you need to set the " "$SRHT_PATH environment variable to the path of the " "core srht module.") elif not os.path.isdir(srht_path): raise Exception( "The $SRHT_PATH environment variable points to an invalid " "directory: {}".format(srht_path)) make = os.environ.get("MAKE", "make")
final_install_path = sys.prefix # sys.prefix points to the virtual environment root isvirtual = True else: isvirtual = False try: final_install_path = site.getuserbase() except: import os # some implementations do not provide compatible 'site' package, assume default Linux behavior final_install_path = os.getenv('HOME') + "/.local/" # check if using OSX Framework environment isosxframework = False if sys.platform == 'darwin': try: if 'python/site-packages' in site.getusersitepackages(): # appears to be Mac Framework using Library/Python/X.Y/lib/python/site-packages isosxframework = True except: # cannot determine if using Mac Framework pass # setup cmake arguments cmake_args = [ '-DCMAKE_BUILD_TYPE=Release', '-DBUILD_SHARED_LIBS=ON', '-DTasmanian_ENABLE_RECOMMENDED:BOOL=ON', '-DTasmanian_ENABLE_PYTHON:BOOL=ON', '-DPYTHON_EXECUTABLE:PATH={0:1s}'.format(sys.executable), '-DTasmanian_python_pip_final:PATH={0:1s}/'.format(final_install_path), ]
def getusersitepackages(): return [site.getusersitepackages()]
def init(cfgfile=''): '''Initialize configuration. Import config settings from settings.cfg if this exists, if it doesn't create an initial config file''' rundir = '' srcdir = '' # If BlueSky is run from a compiled bundle instead of from source, # adjust the startup path and change the path of # configurable files to $home/bluesky if getattr(sys, 'frozen', False): srcdir = os.path.dirname(sys.executable) rundir = os.path.join(os.path.expanduser('~'), 'bluesky') # If BlueSky is installed as a python package the location of the data files need to # be adjusted so that importing will not fail when copying config file below if not os.path.isfile(os.path.join(rundir, 'data/default.cfg')): # collate list of possible data install roots root_dirs = site.getusersitepackages() root_dirs = [root_dirs] if isinstance(root_dirs, str) else root_dirs root_dirs += site.getsitepackages() # search for bluesky shared data directory for root_dir in root_dirs: dirpath = os.path.join(root_dir, 'share', 'bluesky') if os.path.exists(dirpath): srcdir = dirpath break datadir = os.path.join(rundir, 'data') cachedir = os.path.join(rundir, 'data/cache') badadir = os.path.join(rundir, 'data/performance/BADA') badasrc = os.path.join(srcdir, 'data/performance/BADA') perfdir = os.path.join(srcdir, 'data/performance') gfxdir = os.path.join(srcdir, 'data/graphics') navdir = os.path.join(srcdir, 'data/navdata') scnsrc = os.path.join(srcdir, 'scenario') scndir = os.path.join(rundir, 'scenario') outdir = os.path.join(rundir, 'output') plgsrc = os.path.join(srcdir, 'plugins') plgdir = os.path.join(rundir, 'plugins') configsrc = os.path.join(srcdir, 'data/default.cfg') if not cfgfile: cfgfile = os.path.join(rundir, 'settings.cfg') # Check if alternate config file is passed for i in range(len(sys.argv)): if len(sys.argv) > i + 1: if sys.argv[i] == '--config-file': cfgfile = sys.argv[i + 1] elif sys.argv[i] == '--scenfile': globals()['scenfile'] = sys.argv[i + 1] # Create config file if it doesn't exist yet. Ask for gui settings if bluesky # was started with BlueSky.py if not os.path.isfile(cfgfile): print() print( 'No config file settings.cfg found in your BlueSky starting directory!' ) print() print( 'This config file contains several default settings related to the simulation loop and the graphics.' ) print( 'A default version will be generated, which you can change if necessary before the next time you run BlueSky.' ) print() with open(configsrc, 'r') as fin, open(cfgfile, 'w') as fout: for line in fin: if line[:9] == 'data_path': line = "data_path = '" + datadir.replace('\\', '/') + "'\n" if line[:10] == 'cache_path': line = "cache_path = '" + cachedir.replace('\\', '/') + "'\n" elif line[:8] == 'log_path': line = "log_path = '" + outdir.replace('\\', '/') + "'\n" elif line[:13] == 'scenario_path': line = "scenario_path = '" + scndir.replace('\\', '/') + "'\n" elif line[:11] == 'plugin_path': line = "plugin_path = '" + plgdir.replace('\\', '/') + "'\n" elif line[:14] == 'perf_path_bada': line = "perf_path_bada = '" + badadir.replace('\\', '/') + "'\n" elif line[:9] == 'perf_path': line = "perf_path = '" + perfdir.replace('\\', '/') + "'\n" elif line[:8] == 'gfx_path': line = "gfx_path = '" + gfxdir.replace('\\', '/') + "'\n" elif line[:12] == 'navdata_path': line = "navdata_path = '" + navdir.replace('\\', '/') + "'\n" fout.write(line) else: print(f'Reading config from {cfgfile}') exec(compile(open(cfgfile).read(), cfgfile, 'exec'), globals()) # Update cachedir with python version-specific subfolder cachedir = os.path.join(cachedir, 'py%d' % sys.version_info[0]) globals()['cache_path'] = cachedir # Store name of config file globals()['_cfgfile'] = cfgfile # Create default directories if they don't exist yet for d in (outdir, cachedir): if not os.path.isdir(d): print('Creating directory "%s"' % d) os.makedirs(d) for d in [(badasrc, badadir), (scnsrc, scndir), (plgsrc, plgdir)]: if not os.path.isdir(d[1]): print('Creating directory "%s", and copying default files' % d[1]) try: shutil.copytree(*d) except FileNotFoundError: print('Unable to copy "%s" files to "%s"' % (d[0], d[1]), file=sys.stderr) return True
import site from pathlib import Path myPackagePath = Path(__file__).parent.absolute() pathspec = r""" # Generated by GST's installer (install_GST.py) # In the lines below, list the paths where Python should look for # GateSetTomography-supplied modules, one directory per line. # # If a directory does not exist when Python is started, it will be ignored. %s """ % myPackagePath print("Adding path:", myPackagePath) usp = Path(site.getusersitepackages()) usp.mkdir(parents=True, exist_ok=True) uspfile = usp / 'GST.pth' with open(str(uspfile), 'w') as f: f.write(pathspec) print('Wrote to {}'.format(uspfile)) print("GST package installed successfully!")
def _installed_in_user(): try: return __file__.startswith(site.getusersitepackages()) except (TypeError, AttributeError): return False
# Read/write function pointer types. _I2C_READ_FUNC = CFUNCTYPE(c_int, c_ubyte, c_ubyte, POINTER(c_ubyte), c_ubyte) _I2C_WRITE_FUNC = CFUNCTYPE(c_int, c_ubyte, c_ubyte, POINTER(c_ubyte), c_ubyte) # Load VL53L1X shared lib _POSSIBLE_LIBRARY_LOCATIONS = [os.path.dirname(os.path.realpath(__file__))] try: _POSSIBLE_LIBRARY_LOCATIONS += site.getsitepackages() except AttributeError: pass try: _POSSIBLE_LIBRARY_LOCATIONS += [site.getusersitepackages()] except AttributeError: pass for lib_location in _POSSIBLE_LIBRARY_LOCATIONS: files = glob.glob(lib_location + "/vl53l1x_python*.so") if len(files) > 0: lib_file = files[0] try: _TOF_LIBRARY = CDLL(lib_file) #print("Using: " + lib_location + "/vl51l1x_python.so") break except OSError: #print(lib_location + "/vl51l1x_python.so not found") pass else:
#!/usr/bin/python #setgapth.py Completion_Message = \ """ Python pth file Ga.pth for all modules of galgebra has been created and placed in directory appropriate for Linux, Windows, or OSX. Note that if Ga.pth already exists the old version will be deleted. """ import os, sys, site from os.path import isdir cur_dir = os.path.abspath('.') if site.ENABLE_USER_SITE and isdir(site.getusersitepackages()): dist_pkgs = site.getusersitepackages() else: dist_pkgs = site.getsitepackages()[0] if os.name == 'posix' or os.name == 'mac': pth_name = dist_pkgs + '/Ga.pth' if os.path.exists(pth_name): os.system('rm -f ' + pth_name) if os.name == 'nt': dist_lst = dist_pkgs.split('\\') pth_name = dist_lst[0] + '\\' + dist_lst[1] + '\\Ga.pth' if os.path.exists(pth_name): os.system('del ' + pth_name)
def update_event(self, inp=-1): self.set_output_val(0, site.getusersitepackages())
# Note: using realpath due to tmp dirs on OSX being symlinks src_prefix = os.path.abspath(src_prefix) # FIXME doesn't account for venv linked to global site-packages site_packages = sysconfig.get_path("purelib") # type: Optional[str] # This is because of a bug in PyPy's sysconfig module, see # https://bitbucket.org/pypy/pypy/issues/2506/sysconfig-returns-incorrect-paths # for more information. if platform.python_implementation().lower() == "pypy": site_packages = distutils_sysconfig.get_python_lib() try: # Use getusersitepackages if this is present, as it ensures that the # value is initialised properly. user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE user_dir = expanduser('~') if WINDOWS: bin_py = os.path.join(sys.prefix, 'Scripts') bin_user = os.path.join(user_site, 'Scripts') # buildout uses 'bin' on Windows too? if not os.path.exists(bin_py): bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') config_basename = 'pip.ini' legacy_storage_dir = os.path.join(user_dir, 'pip') legacy_config_file = os.path.join(
PATH_LIB32 = "prebuilt/win32/keystone.dll" # package name can be 'keystone-engine' or 'keystone-engine-windows' PKG_NAME = 'keystone-engine' if os.path.exists(PATH_LIB64) and os.path.exists(PATH_LIB32): PKG_NAME = 'keystone-engine-windows' VERSION = '0.9.1-3' SYSTEM = sys.platform # virtualenv breaks import, but get_python_lib() will work. SITE_PACKAGES = os.path.join(get_python_lib(), "keystone") if "--user" in sys.argv: try: from site import getusersitepackages SITE_PACKAGES = os.path.join(getusersitepackages(), "keystone") except ImportError: pass SETUP_DATA_FILES = [] # adapted from commit e504b81 of Nguyen Tan Cong # Reference: https://docs.python.org/2/library/platform.html#cross-platform is_64bits = sys.maxsize > 2**32 def copy_sources(): """Copy the C sources into the source directory. This rearranges the source files under the python distribution directory. """
bGlobalInstall = True print("Installing globally...\n") if bGlobalInstall: spList = site.getsitepackages() print(spList) spDir = spList[0] if not "site-packages" in spDir: # prefer the first directory having "site-packages" in the name. for d in spList: if "site-packages" in d: spDir = d break else: spDir = site.getusersitepackages() print("Installing to site-packages directory: " + spDir) # if the spDir does not exist, create it. if not os.path.exists(spDir): print("creating directory " + spDir) os.makedirs(spDir) print("copying chilkat.py to " + spDir) shutil.copy("chilkat.py", spDir) if mySystem == "Windows": print("copying _chilkat.pyd to " + spDir) shutil.copy("_chilkat.pyd", spDir) else:
import os import sys from setuptools import setup # Checking if obsolete versions are installed in the machine import shutil import site IS_VIRTUAL_ENV = False # Get packagesPaths depending on whether the user launched it with sudo or not if sys.platform == 'win32': # This will throw two folders, but we need the first one only. Typically: # ['c:\\Users\\<a_user>\\AppData\\Roaming\\Python\\Python27\\site-packages'] packagesPaths = site.getusersitepackages()[0] print "[*] The installation is going to be run as superuser." else: # We need this verification because Windows does not have a wrapper ofr os.geteuid() if not os.geteuid() == 0: try: packagesPaths = site.getusersitepackages() print "[*] The installation has not been launched as superuser." except: IS_VIRTUAL_ENV = True else: # This will throw two folders, but we need the first one only: # ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] packagesPaths = site.getsitepackages()[0] print "[*] The installation is going to be run as superuser."
return os.path.abspath(src_prefix) # FIXME doesn't account for venv linked to global site-packages site_packages = sysconfig.get_path("purelib") # type: Optional[str] # This is because of a bug in PyPy's sysconfig module, see # https://bitbucket.org/pypy/pypy/issues/2506/sysconfig-returns-incorrect-paths # for more information. if platform.python_implementation().lower() == "pypy": site_packages = distutils_sysconfig.get_python_lib() try: # Use getusersitepackages if this is present, as it ensures that the # value is initialised properly. user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE if WINDOWS: bin_py = os.path.join(sys.prefix, 'Scripts') bin_user = os.path.join(user_site, 'Scripts') # buildout uses 'bin' on Windows too? if not os.path.exists(bin_py): bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') else: bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') # Forcing to use /usr/local/bin for standard macOS framework installs
try: # if resources dir is not available in CWD, try the # libs dir (site-packages) for the current Python from distutils.sysconfig import get_python_lib paths_to_check.append( os.path.normcase( os.path.join(get_python_lib(), "Nagstamon", "resources"))) except Exception: pass # if we're still out of luck, maybe this was a user scheme install try: import site site.getusersitepackages() # make sure USER_SITE is set paths_to_check.append( os.path.normcase( os.path.join(site.USER_SITE, "Nagstamon", "resources"))) except Exception: pass # add directory nagstamon.py where nagstamon.py resides for cases like 0install without installed pkg-resources paths_to_check.append( os.sep.join(sys.argv[0].split(os.sep)[:-1] + ["Nagstamon", "resources"])) for path in paths_to_check: if os.path.exists(path): RESOURCES = path break