我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.extsep()。
def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" if known_paths is None: known_paths = _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if not sitedircase in known_paths: sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return names.sort() for name in names: if name.endswith(os.extsep + "pth"): addpackage(sitedir, name, known_paths) if reset: known_paths = None return known_paths
def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" if known_paths is None: known_paths = _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if not sitedircase in known_paths: sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return dotpth = os.extsep + "pth" names = [name for name in names if name.endswith(dotpth)] for name in sorted(names): addpackage(sitedir, name, known_paths) if reset: known_paths = None return known_paths
def refactor_dir(self, dir_name, write=False, doctests_only=False): """Descends down a directory and refactor every Python file found. Python files are assumed to have a .py extension. Files and subdirectories starting with '.' are skipped. """ py_ext = os.extsep + "py" for dirpath, dirnames, filenames in os.walk(dir_name): self.log_debug("Descending into %s", dirpath) dirnames.sort() filenames.sort() for name in filenames: if (not name.startswith(".") and os.path.splitext(name)[1] == py_ext): fullname = os.path.join(dirpath, name) self.refactor_file(fullname, write, doctests_only) # Modify dirnames in-place to remove subdirs with leading dots dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
def addsitedir(sitedir): global _dirs_in_sys_path if _dirs_in_sys_path is None: _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if not sitedircase in _dirs_in_sys_path: sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return names.sort() for name in names: if name[-4:] == os.extsep + "pth": addpackage(sitedir, name) if reset: _dirs_in_sys_path = None
def convert(cls, report, data): "converts the report data to another mimetype if necessary" input_format = report.template_extension output_format = report.extension or report.template_extension if output_format in MIMETYPES: return output_format, data fd, path = tempfile.mkstemp(suffix=(os.extsep + input_format), prefix='trytond_') oext = FORMAT2EXT.get(output_format, output_format) with os.fdopen(fd, 'wb+') as fp: fp.write(data) cmd = ['unoconv', '--connection=%s' % config.get('report', 'unoconv'), '-f', oext, '--stdout', path] try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) stdoutdata, stderrdata = proc.communicate() if proc.wait() != 0: raise Exception(stderrdata) return oext, stdoutdata finally: os.remove(path)
def db_filepath(profile_paths: Dict[str, PathLike], filenames: str='places', ext='sqlite') -> Dict[str, PathLike]: """ Yields the path for the next database file. Exits program if browser info or profile directory path are invalid. Accepts profile directory path. Optional: file name(s), extensions (default is sqlite) """ try: ext_joiner = '' if ext[0] in {os.extsep, '.'} else os.extsep # if a . in ext arg, doesn't add another except (TypeError, IndexError): # if file doesn't have an ext, ext arg is empty, doesn't add the `.` ext_joiner, ext = ('', '') if filenames is None: filenames = _db_files(profile_paths=profile_paths, ext=ext) filenames = [filenames] file_names = [ext_joiner.join([file_, ext]) for file_ in filenames] try: return {profile_name: os.path.join(profile_path_, file_name_) for profile_name, profile_path_ in profile_paths.items() for file_name_ in file_names} except TypeError as excep: print('Missing value: browser name or profile path', excep, sep='\n') if debug: raise excep os.sys.exit()
def get_file_name(): datetimenow = datetime.now() datestr = datetimenow.strftime("%Y-%m-%d") timestr = datetimenow.strftime("%H-%M-%S") file_name = None try: test_class_path, test_method_name = find_test_caller_in_stack() test_package_path, test_file_name = os.path.split(test_class_path) # identify main package name from the class # for example: pybot/whatsapp/feature/AppPageFeature.py -> feature test_package_name = test_package_path.split(os.sep)[-1:][0] test_class_name = test_file_name.split(os.extsep)[0] file_name = "%s-%s-%s-%s" % ( test_package_name, test_class_name, datestr, timestr ) except ValueError: file_name = "%s-%s" % (datestr, timestr) return file_name
def download_file(self, bucket, key, filename, extra_args=None, callback=None): """Download an S3 object to a file. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.download_file() directly. """ # This method will issue a ``head_object`` request to determine # the size of the S3 object. This is used to determine if the # object is downloaded in parallel. if extra_args is None: extra_args = {} self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) object_size = self._object_size(bucket, key, extra_args) temp_filename = filename + os.extsep + random_file_extension() try: self._download_file(bucket, key, temp_filename, object_size, extra_args, callback) except Exception: logger.debug("Exception caught in download_file, removing partial " "file: %s", temp_filename, exc_info=True) self._osutil.remove_file(temp_filename) raise else: self._osutil.rename_file(temp_filename, filename)
def save_image(file_, extension, message, name, email, branch='master'): """ Save image to github as a commit :param file_: Open file object containing image :param: Extension to use for saved filename :param message: Commit message to save image with :param name: Name of user committing image :param email: Email address of user committing image :param branch: Branch to save image to :returns: Public URL to image or None if not successfully saved """ file_name = secure_filename('%s%s%s' % (str(uuid.uuid4()), os.extsep, extension)) path = os.path.join(main_image_path(), file_name) url = None if commit_image_to_github(path, message, file_, name, email, branch=branch) is not None: url = github_url_from_upload_path(path, file_name, branch=branch) return url
def addsitedir(sitedir): global _dirs_in_sys_path if _dirs_in_sys_path is None: _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if sitedircase not in _dirs_in_sys_path: sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return names.sort() for name in names: if name[-4:] == os.extsep + "pth": addpackage(sitedir, name) if reset: _dirs_in_sys_path = None
def test_execute_bit_not_copied(self): # Issue 6070: under posix .pyc files got their execute bit set if # the .py file had the execute bit set, but they aren't executable. with temp_umask(0o022): sys.path.insert(0, os.curdir) try: fname = TESTFN + os.extsep + "py" open(fname, 'w').close() os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) fn = imp.cache_from_source(fname) unlink(fn) __import__(TESTFN) if not os.path.exists(fn): self.fail("__import__ did not result in creation of " "either a .pyc or .pyo file") s = os.stat(fn) self.assertEqual(stat.S_IMODE(s.st_mode), stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) finally: del sys.path[0] remove_files(TESTFN) unload(TESTFN)
def _make_pkg(self, source, depth, mod_base="runpy_test"): pkg_name = "__runpy_pkg__" test_fname = mod_base+os.extsep+"py" pkg_dir = sub_dir = tempfile.mkdtemp() if verbose: print(" Package tree in:", sub_dir) sys.path.insert(0, pkg_dir) if verbose: print(" Updated sys.path:", sys.path[0]) for i in range(depth): sub_dir = os.path.join(sub_dir, pkg_name) pkg_fname = self._add_pkg_dir(sub_dir) if verbose: print(" Next level in:", sub_dir) if verbose: print(" Created:", pkg_fname) mod_fname = os.path.join(sub_dir, test_fname) mod_file = open(mod_fname, "w") mod_file.write(source) mod_file.close() if verbose: print(" Created:", mod_fname) mod_name = (pkg_name+".")*depth + mod_base return pkg_dir, mod_fname, mod_name
def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None): zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) zip_file = zipfile.ZipFile(zip_name, 'w') if name_in_zip is None: parts = script_name.split(os.sep) if len(parts) >= 2 and parts[-2] == '__pycache__': legacy_pyc = make_legacy_pyc(source_from_cache(script_name)) name_in_zip = os.path.basename(legacy_pyc) script_name = legacy_pyc else: name_in_zip = os.path.basename(script_name) zip_file.write(script_name, name_in_zip) zip_file.close() #if test.support.verbose: # zip_file = zipfile.ZipFile(zip_name, 'r') # print 'Contents of %r:' % zip_name # zip_file.printdir() # zip_file.close() return zip_name, os.path.join(zip_name, name_in_zip)
def test_badimport(self): # This tests the fix for issue 5230, where if pydoc found the module # but the module had an internal import error pydoc would report no doc # found. modname = 'testmod_xyzzy' testpairs = ( ('i_am_not_here', 'i_am_not_here'), ('test.i_am_not_here_either', 'test.i_am_not_here_either'), ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'), ('i_am_not_here.{}'.format(modname), 'i_am_not_here'), ('test.{}'.format(modname), 'test.{}'.format(modname)), ) sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py" for importstring, expectedinmsg in testpairs: with open(sourcefn, 'w') as f: f.write("import {}\n".format(importstring)) result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii") expected = badimport_pattern % (modname, expectedinmsg) self.assertEqual(expected, result)