我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用site.getsitepackages()。
def startRyu(self, learning_switch=True): # start Ryu controller with rest-API python_install_path = site.getsitepackages()[0] # ryu default learning switch #ryu_path = python_install_path + '/ryu/app/simple_switch_13.py' #custom learning switch that installs a default NORMAL action in the ovs switches dir_path = os.path.dirname(os.path.realpath(__file__)) ryu_path = dir_path + '/son_emu_simple_switch_13.py' ryu_path2 = python_install_path + '/ryu/app/ofctl_rest.py' # change the default Openflow controller port to 6653 (official IANA-assigned port number), as used by Mininet # Ryu still uses 6633 as default ryu_option = '--ofp-tcp-listen-port' ryu_of_port = '6653' ryu_cmd = 'ryu-manager' FNULL = open("/tmp/ryu.log", 'w') if learning_switch: self.ryu_process = Popen([ryu_cmd, ryu_path, ryu_path2, ryu_option, ryu_of_port], stdout=FNULL, stderr=FNULL) LOG.debug('starting ryu-controller with {0}'.format(ryu_path)) LOG.debug('starting ryu-controller with {0}'.format(ryu_path2)) else: # no learning switch, but with rest api self.ryu_process = Popen([ryu_cmd, ryu_path2, ryu_option, ryu_of_port], stdout=FNULL, stderr=FNULL) LOG.debug('starting ryu-controller with {0}'.format(ryu_path2)) time.sleep(1)
def getsitepackages(): """ Return only one item as list with one item. """ # For now used only on Windows. Raise Exception for other platforms. if is_win: pths = [os.path.join(sys.prefix, 'Lib', 'site-packages')] # Include Real sys.prefix for virtualenv. if is_virtualenv: pths.append(os.path.join(base_prefix, 'Lib', 'site-packages')) return pths else: # TODO Implement for Python 2.6 on other platforms. raise NotImplementedError() # Function to reload a module - used to reload module 'PyInstaller.config' for tests. # imp module is deprecated since Python 3.4.
def test_getsitepackages(self): site.PREFIXES = ['xoxo'] dirs = site.getsitepackages() if sys.platform in ('os2emx', 'riscos'): self.assertEqual(len(dirs), 1) wanted = os.path.join('xoxo', 'Lib', 'site-packages') self.assertEqual(dirs[0], wanted) elif os.sep == '/': # OS X, Linux, FreeBSD, etc self.assertEqual(len(dirs), 2) wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], 'site-packages') self.assertEqual(dirs[0], wanted) wanted = os.path.join('xoxo', 'lib', 'site-python') self.assertEqual(dirs[1], wanted) else: # other platforms self.assertEqual(len(dirs), 2) self.assertEqual(dirs[0], 'xoxo') wanted = os.path.join('xoxo', 'lib', 'site-packages') self.assertEqual(dirs[1], wanted)
def get_site_packages_directory(): """Print and return the site-packages directory. Examples --------- >>> loc = tl.ops.get_site_packages_directory() """ import site try: loc = site.getsitepackages() print(" tl.ops : site-packages in ", loc) return loc except: print(" tl.ops : Cannot find package dir from virtual environment") return False #
def get_data_file(file_name): path = None if os.path.isfile('pv/%s' % file_name): path = 'pv/%s' % file_name elif os.path.isfile(site.getusersitepackages()+'/cse/'+file_name): path = site.getusersitepackages()+'/cse/'+file_name else: sp = site.getsitepackages() if isinstance(sp, list): for item in sp: if os.path.isfile(item+'/cse/'+file_name): path = item+'/cse/'+file_name break elif os.path.isfile(sp+'/cse/'+file_name): path = sp+'/cse/'+file_name content = '' if path is not None: with open(path) as f: content = f.read() return content
def find_modules_from_path(import_path): import_from_path(import_path) site_dirs = site.getsitepackages() lib_dirs = [os.path.dirname(path) for path in site_dirs] for module in sys.modules.values(): path = getattr(module, '__file__', '') if path[-4:] in ('.pyo', '.pyc'): path = path[:-1] if path and os.path.exists(path): if all(not path.startswith(lib_dir) for lib_dir in lib_dirs): yield module
def test_getsitepackages(self): site.PREFIXES = ['xoxo'] dirs = site.getsitepackages() if sys.platform in ('os2emx', 'riscos'): self.assertEqual(len(dirs), 1) wanted = os.path.join('xoxo', 'Lib', 'site-packages') self.assertEqual(dirs[0], wanted) elif (sys.platform == "darwin" and sysconfig.get_config_var("PYTHONFRAMEWORK")): # OS X framework builds site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 3) wanted = os.path.join('/Library', sysconfig.get_config_var("PYTHONFRAMEWORK"), sys.version[:3], 'site-packages') self.assertEqual(dirs[2], wanted) elif os.sep == '/': # OS X non-framwework builds, Linux, FreeBSD, etc self.assertEqual(len(dirs), 2) wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], 'site-packages') self.assertEqual(dirs[0], wanted) wanted = os.path.join('xoxo', 'lib', 'site-python') self.assertEqual(dirs[1], wanted) else: # other platforms self.assertEqual(len(dirs), 2) self.assertEqual(dirs[0], 'xoxo') wanted = os.path.join('xoxo', 'lib', 'site-packages') self.assertEqual(dirs[1], wanted)
def find_DST(): """Find where this package should be installed to. """ if SYS_NAME == "Windows": return os.path.join(site.getsitepackages()[1], PKG_NAME) elif SYS_NAME in ["Darwin", "Linux"]: return os.path.join(site.getsitepackages()[0], PKG_NAME)
def test_s_option(self): usersite = site.USER_SITE self.assertIn(usersite, sys.path) env = os.environ.copy() rc = subprocess.call([sys.executable, '-c', 'import sys; sys.exit(%r in sys.path)' % usersite], env=env) self.assertEqual(rc, 1) env = os.environ.copy() rc = subprocess.call([sys.executable, '-s', '-c', 'import sys; sys.exit(%r in sys.path)' % usersite], env=env) if usersite == site.getsitepackages()[0]: self.assertEqual(rc, 1) else: self.assertEqual(rc, 0) env = os.environ.copy() env["PYTHONNOUSERSITE"] = "1" rc = subprocess.call([sys.executable, '-c', 'import sys; sys.exit(%r in sys.path)' % usersite], env=env) if usersite == site.getsitepackages()[0]: self.assertEqual(rc, 1) else: self.assertEqual(rc, 0) env = os.environ.copy() env["PYTHONUSERBASE"] = "/tmp" rc = subprocess.call([sys.executable, '-c', 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'], env=env) self.assertEqual(rc, 1)
def get_site_packages_directory(): """Print and return the site-packages directory. Examples --------- >>> loc = tl.ops.get_site_packages_directory() """ import site try: loc = site.getsitepackages() print(" tl.ops : site-packages in ", loc) return loc except: print(" tl.ops : Cannot find package dir from virtual environment") return False
def test_getsitepackages(self): site.PREFIXES = ['xoxo'] dirs = site.getsitepackages() if sys.platform in ('os2emx', 'riscos'): self.assertEqual(len(dirs), 1) wanted = os.path.join('xoxo', 'Lib', 'site-packages') self.assertEqual(dirs[0], wanted) elif '__pypy__' in sys.builtin_module_names: self.assertEquals(len(dirs), 1) wanted = os.path.join('xoxo', 'site-packages') self.assertEquals(dirs[0], wanted) elif (sys.platform == "darwin" and sysconfig.get_config_var("PYTHONFRAMEWORK")): # OS X framework builds site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 3) wanted = os.path.join('/Library', sysconfig.get_config_var("PYTHONFRAMEWORK"), sys.version[:3], 'site-packages') self.assertEqual(dirs[2], wanted) elif os.sep == '/': # OS X non-framwework builds, Linux, FreeBSD, etc self.assertEqual(len(dirs), 2) wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], 'site-packages') self.assertEqual(dirs[0], wanted) wanted = os.path.join('xoxo', 'lib', 'site-python') self.assertEqual(dirs[1], wanted) else: # other platforms self.assertEqual(len(dirs), 2) self.assertEqual(dirs[0], 'xoxo') wanted = os.path.join('xoxo', 'lib', 'site-packages') self.assertEqual(dirs[1], wanted)
def test_getsitepackages(self): site.PREFIXES = ['xoxo'] dirs = site.getsitepackages() if (sys.platform == "darwin" and sysconfig.get_config_var("PYTHONFRAMEWORK")): # OS X framework builds site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 3) wanted = os.path.join('/Library', sysconfig.get_config_var("PYTHONFRAMEWORK"), sys.version[:3], 'site-packages') self.assertEqual(dirs[2], wanted) elif os.sep == '/': # OS X non-framwework builds, Linux, FreeBSD, etc self.assertEqual(len(dirs), 2) wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], 'site-packages') self.assertEqual(dirs[0], wanted) wanted = os.path.join('xoxo', 'lib', 'site-python') self.assertEqual(dirs[1], wanted) else: # other platforms self.assertEqual(len(dirs), 2) self.assertEqual(dirs[0], 'xoxo') wanted = os.path.join('xoxo', 'lib', 'site-packages') self.assertEqual(dirs[1], wanted)
def get_site_packages_directory(): """Print and return the site-packages directory. Examples --------- >>> loc = tl.ops.get_site_packages_directory() """ import site try: loc = site.getsitepackages() print("[TL] tl.ops : site-packages in ", loc) return loc except: print("[TL] tl.ops : Cannot find package dir from virtual environment") return False
def get_site_packages() -> list: try: return list(site.getsitepackages()) except Exception: return []
def get_binaries_directory(): """Return the installation directory, or None http://stackoverflow.com/questions/36187264""" if '--user' in sys.argv: paths = (site.getusersitepackages(),) else: if hasattr(site, 'getsitepackages'): print("cmany setup: site-packages", site.getsitepackages()) print("cmany setup: site-user-packages", site.getusersitepackages()) print("cmany setup: site-prefix", os.path.dirname(sys.executable)) paths = site.getsitepackages() else: print("cmany setup: no site.getsitepackages()...") py_prefix = os.path.dirname(sys.executable) paths = [ py_prefix + '/lib/site-packages', py_prefix + '/lib/site-packages', py_prefix + '/lib', ] py_version = '{}.{}'.format(sys.version_info[0], sys.version_info[1]) paths += (s.format(py_version) for s in ( sys.prefix + '/lib/python{}/site-packages/', sys.prefix + '/lib/python{}/dist-packages/', sys.prefix + '/local/lib/python{}/site-packages/', sys.prefix + '/local/lib/python{}/dist-packages/', '/Library/Python/{}/site-packages/', )) for path in paths: if os.path.exists(path): print('cmany setup: installation path:', path) return path raise Exception('cmany setup: no installation path found', file=sys.stderr) return None
def get_site_dirs(): # return a list of 'site' dirs sitedirs = [_f for _f in os.environ.get('PYTHONPATH', '').split(os.pathsep) if _f] prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: if sys.platform in ('os2emx', 'riscos'): sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) elif os.sep == '/': sitedirs.extend([ os.path.join( prefix, "lib", "python" + sys.version[:3], "site-packages", ), os.path.join(prefix, "lib", "site-python"), ]) else: sitedirs.extend([ prefix, os.path.join(prefix, "lib", "site-packages"), ]) if sys.platform == 'darwin': # for framework builds *only* we add the standard Apple # locations. Currently only per-user, but /Library and # /Network/Library could be added too if 'Python.framework' in prefix: home = os.environ.get('HOME') if home: home_sp = os.path.join( home, 'Library', 'Python', sys.version[:3], 'site-packages', ) sitedirs.append(home_sp) lib_paths = get_path('purelib'), get_path('platlib') for site_lib in lib_paths: if site_lib not in sitedirs: sitedirs.append(site_lib) if site.ENABLE_USER_SITE: sitedirs.append(site.USER_SITE) try: sitedirs.extend(site.getsitepackages()) except AttributeError: pass sitedirs = list(map(normalize_path, sitedirs)) return sitedirs
def post_install(): # Install pre-packaged tools to user dir from win32com.client import Dispatch # Package name packageName = 'omSipCreator' # Locate Windows user directory userDir = os.path.expanduser('~') # Config directory configDirUser = os.path.join(userDir, packageName) # Create config directory if it doesn't exist if os.path.isdir(configDirUser) == False: try: os.makedirs(configDirUser) except IOError: msg = 'could not create configuration directory' errorExit(msg) # Install tools # Tools directory toolsDirUser = os.path.join(configDirUser,'tools') if os.path.isdir(toolsDirUser) == False: # No tools directory in user dir, so copy it from location in source or package. Location is # /omsipcreator/conf/tools in 'site-packages' directory (if installed with pip) # Locate site-packages dir (this returns multiple entries) sitePackageDirs = site.getsitepackages() # Assumptions: site package dir is called 'site-packages' and is unique (?) for dir in sitePackageDirs: if 'site-packages'in dir: sitePackageDir = dir # Construct path to tools dir toolsDirPackage = os.path.join(sitePackageDir, packageName, 'tools') # If package tools dir exists, copy it to the user directory if os.path.isdir(toolsDirPackage) == True: try: copytree(toolsDirPackage, toolsDirUser) except IOError: msg = 'could not copy tools directory to ' + toolsDirUser errorExit(msg) # This should never happen but who knows ... else: msg = 'no tools directory found in package' errorExit(msg)
def search_actions(cls): # if we load the actions yet, return them if len(Action.python_files) > 0: return Action.python_files # elsewere, load all the custom actions you find Global.LOGGER.debug("searching for installed actions... it can takes a while") site_packages = site.getsitepackages() Global.LOGGER.debug(f"current path: {os.getcwd()}") # get custom actions in current path Global.LOGGER.debug("looking inside the current directory") tmp_python_files_in_current_directory = glob.glob(f"{os.getcwd()}/*Action.py", recursive=False) Global.LOGGER.debug(f"found {len(tmp_python_files_in_current_directory)} actions in current directory") basenames = list(map(os.path.basename, tmp_python_files_in_current_directory)) tmp_python_files_dict = dict(zip(basenames, tmp_python_files_in_current_directory)) # get custom actions in current /Action subdir Global.LOGGER.debug("looking inside any ./Actions subdirectory") tmp_python_files_in_current_action_subdirectory = glob.glob(f"{os.getcwd()}/**/Actions/*Action.py", recursive=True) Global.LOGGER.debug(f"found {len(tmp_python_files_in_current_action_subdirectory)} actions in a ./Actions subdirectory") for action_file in tmp_python_files_in_current_action_subdirectory: action_filename = os.path.basename(action_file) if action_filename not in tmp_python_files_dict: tmp_python_files_dict[action_filename] = action_file # get custom actions in site_packages directory Global.LOGGER.debug("looking inside the Python environment") for my_site in site_packages: tmp_python_files_in_site_directory = glob.glob(f"{my_site}/**/Actions/*Action.py", recursive=True) Global.LOGGER.debug(f"found {len(tmp_python_files_in_site_directory)} actions in {my_site}") for action_file in tmp_python_files_in_site_directory: action_filename = os.path.basename(action_file) if action_filename not in tmp_python_files_dict: tmp_python_files_dict[action_filename] = action_file # Action.python_files = list(set(tmp_python_files)) action_files = tmp_python_files_dict.values() if len(action_files) > 0: Global.LOGGER.debug(f"{len(action_files)} actions found") if Global.CONFIG_MANAGER.tracing_mode: actions_found = "\n".join(action_files) Global.LOGGER.debug(f"actions found: \n{actions_found}") else: Global.LOGGER.debug(f"no actions found on {my_site}") Action.python_files = action_files return action_files