Python os.curdir() Examples
The following are 30 code examples for showing how to use os.curdir(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
os
, or try the search function
.
Example 1
Project: verge3d-blender-addon Author: Soft8Soft File: server.py License: GNU General Public License v3.0 | 6 votes |
def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib_parse.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path
Example 2
Project: misp42splunk Author: remg427 File: server.py License: GNU Lesser General Public License v3.0 | 6 votes |
def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib_parse.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path
Example 3
Project: misp42splunk Author: remg427 File: server.py License: GNU Lesser General Public License v3.0 | 6 votes |
def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib_parse.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path
Example 4
Project: py Author: pytest-dev File: common.py License: MIT License | 6 votes |
def bestrelpath(self, dest): """ return a string which is a relative path from self (assumed to be a directory) to dest such that self.join(bestrelpath) == dest and if not such path can be determined return dest. """ try: if self == dest: return os.curdir base = self.common(dest) if not base: # can be the case on windows return str(dest) self2base = self.relto(base) reldest = dest.relto(base) if self2base: n = self2base.count(self.sep) + 1 else: n = 0 l = [os.pardir] * n if reldest: l.append(reldest) target = dest.sep.join(l) return target except AttributeError: return str(dest)
Example 5
Project: conan-center-index Author: conan-io File: conanfile.py License: MIT License | 6 votes |
def build(self): use_windows_commands = os.name == 'nt' command = "build" if use_windows_commands else "./build.sh" if self.options.toolset != 'auto': command += " "+str(self.options.toolset) build_dir = os.path.join(self.source_folder, "source") engine_dir = os.path.join(build_dir, "src", "engine") os.chdir(engine_dir) with tools.environment_append({"VSCMD_START_DIR": os.curdir}): if self.options.use_cxx_env: # Allow use of CXX env vars. self.run(command) else: # To avoid using the CXX env vars we clear them out for the build. with tools.environment_append({"CXX": "", "CXXFLAGS": ""}): self.run(command) os.chdir(build_dir) command = os.path.join( engine_dir, "b2.exe" if use_windows_commands else "b2") full_command = \ "{0} --ignore-site-config --prefix=../output --abbreviate-paths install".format( command) self.run(full_command)
Example 6
Project: bugbuzz-python Author: fangpenlin File: ez_setup.py License: MIT License | 6 votes |
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """ Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) zip_name = "setuptools-%s.zip" % version url = download_base + zip_name saveto = os.path.join(to_dir, zip_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto)
Example 7
Project: linter-pylama Author: AtomLinter File: utils.py License: MIT License | 6 votes |
def normalize_path(path, parent=os.curdir): # type: (str, str) -> str """Normalize a single-path. :returns: The normalized path. :rtype: str """ # NOTE(sigmavirus24): Using os.path.sep and os.path.altsep allow for # Windows compatibility with both Windows-style paths (c:\\foo\bar) and # Unix style paths (/foo/bar). separator = os.path.sep # NOTE(sigmavirus24): os.path.altsep may be None alternate_separator = os.path.altsep or '' if separator in path or (alternate_separator and alternate_separator in path): path = os.path.abspath(os.path.join(parent, path)) return path.rstrip(separator + alternate_separator)
Example 8
Project: linter-pylama Author: AtomLinter File: pycodestyle.py License: MIT License | 6 votes |
def normalize_paths(value, parent=os.curdir): """Parse a comma-separated list of paths. Return a list of absolute paths. """ if not value: return [] if isinstance(value, list): return value paths = [] for path in value.split(','): path = path.strip() if '/' in path: path = os.path.abspath(os.path.join(parent, path)) paths.append(path.rstrip('/')) return paths
Example 9
Project: recruit Author: Frank-qlu File: util.py License: Apache License 2.0 | 6 votes |
def convert_path(pathname): """Return 'pathname' as a name that will work on the native filesystem. The path is split on '/' and put back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if not pathname: return pathname if pathname[0] == '/': raise ValueError("path '%s' cannot be absolute" % pathname) if pathname[-1] == '/': raise ValueError("path '%s' cannot end with '/'" % pathname) paths = pathname.split('/') while os.curdir in paths: paths.remove(os.curdir) if not paths: return os.curdir return os.path.join(*paths)
Example 10
Project: Nest Author: ZhouYanzhao File: modules.py License: MIT License | 6 votes |
def _update_namespaces(self) -> None: """Get the available namespaces. """ # user defined search paths dir_list = set() self.namespaces = dict() for k, v in settings['SEARCH_PATHS'].items(): if os.path.isdir(v): meta_path = os.path.join(v, settings['NAMESPACE_CONFIG_FILENAME']) meta = U.load_yaml(meta_path)[0] if os.path.exists(meta_path) else dict() meta['module_path'] = os.path.abspath(os.path.join(v, meta.get('module_path', './'))) if os.path.isdir(meta['module_path']): self.namespaces[k] = meta dir_list.add(meta['module_path']) else: U.alert_msg('Namespace "%s" has an invalid module path "%s".' % (k, meta['module_path'])) # current path current_path = os.path.abspath(os.curdir) if not current_path in dir_list: self.namespaces['main'] = dict(module_path=current_path)
Example 11
Project: flyover Author: jeremybmerrill File: ez_setup.py License: MIT License | 6 votes |
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """ Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) zip_name = "setuptools-%s.zip" % version url = download_base + zip_name saveto = os.path.join(to_dir, zip_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto)
Example 12
Project: jbox Author: jpush File: util.py License: MIT License | 6 votes |
def convert_path(pathname): """Return 'pathname' as a name that will work on the native filesystem. The path is split on '/' and put back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if not pathname: return pathname if pathname[0] == '/': raise ValueError("path '%s' cannot be absolute" % pathname) if pathname[-1] == '/': raise ValueError("path '%s' cannot end with '/'" % pathname) paths = pathname.split('/') while os.curdir in paths: paths.remove(os.curdir) if not paths: return os.curdir return os.path.join(*paths)
Example 13
Project: jbox Author: jpush File: build_ext.py License: MIT License | 6 votes |
def copy_extensions_to_source(self): build_py = self.get_finalized_command('build_py') for ext in self.extensions: fullname = self.get_ext_fullname(ext.name) filename = self.get_ext_filename(fullname) modpath = fullname.split('.') package = '.'.join(modpath[:-1]) package_dir = build_py.get_package_dir(package) dest_filename = os.path.join(package_dir, os.path.basename(filename)) src_filename = os.path.join(self.build_lib, filename) # Always copy, even if source is older than destination, to ensure # that the right extensions for the current Python/platform are # used. copy_file( src_filename, dest_filename, verbose=self.verbose, dry_run=self.dry_run ) if ext._needs_stub: self.write_stub(package_dir or os.curdir, ext, True)
Example 14
Project: Adafruit_Python_BMP Author: adafruit File: ez_setup.py License: MIT License | 6 votes |
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """ Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) zip_name = "setuptools-%s.zip" % version url = download_base + zip_name saveto = os.path.join(to_dir, zip_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto)
Example 15
Project: longclaw Author: JamesRamm File: longclaw.py License: MIT License | 6 votes |
def build_assets(args): """ Build the longclaw assets """ # Get the path to the JS directory asset_path = path.join(path.dirname(longclaw.__file__), 'client') try: # Move into client dir curdir = os.path.abspath(os.curdir) os.chdir(asset_path) print('Compiling assets....') subprocess.check_call(['npm', 'install']) subprocess.check_call(['npm', 'run', 'build']) os.chdir(curdir) print('Complete!') except (OSError, subprocess.CalledProcessError) as err: print('Error compiling assets: {}'.format(err)) raise SystemExit(1)
Example 16
Project: Adafruit_Python_ILI9341 Author: adafruit File: ez_setup.py License: MIT License | 6 votes |
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """ Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) zip_name = "setuptools-%s.zip" % version url = download_base + zip_name saveto = os.path.join(to_dir, zip_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto)
Example 17
Project: Faraday-Software Author: FaradayRF File: helper.py License: GNU General Public License v3.0 | 6 votes |
def getLogger(self): """ Get logger configuration and create instance of a logger """ # Known paths where loggingConfig.ini can exist relpath1 = os.path.join('etc', 'faraday') relpath2 = os.path.join('..', 'etc', 'faraday') setuppath = os.path.join(sys.prefix, 'etc', 'faraday') userpath = os.path.join(os.path.expanduser('~'), '.faraday') self.path = '' # Check all directories until first instance of loggingConfig.ini for location in os.curdir, relpath1, relpath2, setuppath, userpath: try: logging.config.fileConfig(os.path.join(location, "loggingConfig.ini")) self.path = location break except ConfigParser.NoSectionError: pass self._logger = logging.getLogger(self._name) return self._logger
Example 18
Project: benchexec Author: sosy-lab File: model.py License: Apache License 2.0 | 6 votes |
def cmdline_for_run(tool, executable, options, sourcefiles, propertyfile, rlimits): working_directory = tool.working_directory(executable) def relpath(path): return path if os.path.isabs(path) else os.path.relpath(path, working_directory) rel_executable = relpath(executable) if os.path.sep not in rel_executable: rel_executable = os.path.join(os.curdir, rel_executable) args = tool.cmdline( rel_executable, list(options), list(map(relpath, sourcefiles)), relpath(propertyfile) if propertyfile else None, rlimits.copy(), ) assert all(args), "Tool cmdline contains empty or None argument: " + str(args) args = [os.path.expandvars(arg) for arg in args] args = [os.path.expanduser(arg) for arg in args] return args
Example 19
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: utils.py License: Apache License 2.0 | 5 votes |
def save_params(dir_path=os.curdir, epoch=None, name="", params=None, aux_states=None, ctx=mx.cpu()): prefix = os.path.join(dir_path, name) _, param_saving_path, _ = get_saving_path(prefix, epoch) if not os.path.isdir(dir_path) and not (dir_path == ""): os.makedirs(dir_path) save_dict = {('arg:%s' % k): v.copyto(ctx) for k, v in params.items()} save_dict.update({('aux:%s' % k): v.copyto(ctx) for k, v in aux_states.items()}) nd.save(param_saving_path, save_dict) return param_saving_path
Example 20
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: utils.py License: Apache License 2.0 | 5 votes |
def save_misc(dir_path=os.curdir, epoch=None, name="", content=None): prefix = os.path.join(dir_path, name) _, _, misc_saving_path = get_saving_path(prefix, epoch) with open(misc_saving_path, 'w') as fp: json.dump(content, fp) return misc_saving_path
Example 21
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: utils.py License: Apache License 2.0 | 5 votes |
def quick_save_json(dir_path=os.curdir, file_name="", content=None): file_path = os.path.join(dir_path, file_name) if not os.path.isdir(dir_path): os.makedirs(dir_path) with open(file_path, 'w') as fp: json.dump(content, fp) logging.info('Save json into %s' % file_path)
Example 22
Project: jawfish Author: war-and-code File: tempfile.py License: MIT License | 5 votes |
def _candidate_tempdir_list(): """Generate a list of candidate temporary directories which _get_default_tempdir will try.""" dirlist = [] # First, try the environment. for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = _os.getenv(envname) if dirname: dirlist.append(dirname) # Failing that, try OS-specific locations. if _os.name == 'nt': dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) else: dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) # As a last resort, the current directory. try: dirlist.append(_os.getcwd()) except (AttributeError, OSError): dirlist.append(_os.curdir) return dirlist
Example 23
Project: jawfish Author: war-and-code File: tempfile.py License: MIT License | 5 votes |
def _get_default_tempdir(): """Calculate the default directory to use for temporary files. This routine should be called exactly once. We determine whether or not a candidate temp dir is usable by trying to create and write to a file in that directory. If this is successful, the test file is deleted. To prevent denial of service, the name of the test file must be randomized.""" namer = _RandomNameSequence() dirlist = _candidate_tempdir_list() for dir in dirlist: if dir != _os.curdir: dir = _os.path.normcase(_os.path.abspath(dir)) # Try only a few names per directory. for seq in range(100): name = next(namer) filename = _os.path.join(dir, name) try: fd = _os.open(filename, _bin_openflags, 0o600) try: try: with _io.open(fd, 'wb', closefd=False) as fp: fp.write(b'blat') finally: _os.close(fd) finally: _os.unlink(filename) return dir except FileExistsError: pass except OSError: break # no point trying more names in this directory raise FileNotFoundError(_errno.ENOENT, "No usable temporary directory found in %s" % dirlist)
Example 24
Project: pyroma Author: regebro File: projectdata.py License: MIT License | 5 votes |
def __enter__(self): self._old_path = os.path.abspath(os.curdir) if self._old_path in sys.path: sys.path.remove(self._old_path) os.chdir(self._path) if self._path not in sys.path: sys.path.insert(0, self._path) self._path_appended = True else: self._path_appended = False
Example 25
Project: leaguedirector Author: RiotGames File: widgets.py License: Apache License 2.0 | 5 votes |
def respath(*args): directory = os.path.abspath(os.path.join(os.curdir, 'resources')) return os.path.join(directory, *args)
Example 26
Project: bugbuzz-python Author: fangpenlin File: ez_setup.py License: MIT License | 5 votes |
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15): to_dir = os.path.abspath(to_dir) rep_modules = 'pkg_resources', 'setuptools' imported = set(sys.modules).intersection(rep_modules) try: import pkg_resources except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("setuptools>=" + version) return except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.VersionConflict as VC_err: if imported: msg = textwrap.dedent(""" The required version of setuptools (>={version}) is not available, and can't be installed while this script is running. Please install a more recent version first, using 'easy_install -U setuptools'. (Currently using {VC_err.args[0]!r}) """).format(VC_err=VC_err, version=version) sys.stderr.write(msg) sys.exit(2) # otherwise, reload ok del pkg_resources, sys.modules['pkg_resources'] return _do_download(version, download_base, to_dir, download_delay)
Example 27
Project: DNA-GAN Author: Prinsphield File: dataset.py License: MIT License | 5 votes |
def base_dir(self): return os.path.abspath(os.curdir)
Example 28
Project: thingsboard-gateway Author: thingsboard File: tb_gateway.py License: Apache License 2.0 | 5 votes |
def main(): if "logs" not in listdir(curdir): mkdir("logs") TBGatewayService(path.dirname(path.abspath(__file__)) + '/config/tb_gateway.yaml'.replace('/', path.sep))
Example 29
Project: linter-pylama Author: AtomLinter File: utils.py License: MIT License | 5 votes |
def normalize_paths(paths, parent=os.curdir): # type: (Union[Sequence[str], str], str) -> List[str] """Parse a comma-separated list of paths. :returns: The normalized paths. :rtype: [str] """ return [normalize_path(p, parent) for p in parse_comma_separated_list(paths)]
Example 30
Project: linter-pylama Author: AtomLinter File: options.py License: MIT License | 5 votes |
def normalize_path(path, parent=os.curdir): """Normalize a single-path. :returns: The normalized path. :rtype: str """ # NOTE(sigmavirus24): Using os.path.sep allows for Windows paths to # be specified and work appropriately. separator = os.path.sep if separator in path: path = os.path.abspath(os.path.join(parent, path)) return path.rstrip(separator)