query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
set working directory
python
def _set_WorkingDir(self, path): """Sets the working directory """ self._curr_working_dir = path try: mkdir(self.WorkingDir) except OSError: # Directory already exists pass
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L391-L399
set working directory
python
def set_working_directory(self, dirname): """Set current working directory. In the workingdirectory and explorer plugins. """ if dirname: self.main.workingdirectory.chdir(dirname, refresh_explorer=True, refresh_console=False)
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L577-L583
set working directory
python
def set_workdir(self, workdir, chroot=False): """Set the working directory. Cannot be set more than once unless chroot is True""" if not chroot and hasattr(self, "workdir") and self.workdir != workdir: raise ValueError("self.workdir != workdir: %s, %s" % (self.workdir, workdir)) self.workdir = os.path.abspath(workdir) # Files required for the execution. self.input_file = File(os.path.join(self.workdir, "run.abi")) self.output_file = File(os.path.join(self.workdir, "run.abo")) self.files_file = File(os.path.join(self.workdir, "run.files")) self.job_file = File(os.path.join(self.workdir, "job.sh")) self.log_file = File(os.path.join(self.workdir, "run.log")) self.stderr_file = File(os.path.join(self.workdir, "run.err")) self.start_lockfile = File(os.path.join(self.workdir, "__startlock__")) # This file is produced by Abinit if nprocs > 1 and MPI_ABORT. self.mpiabort_file = File(os.path.join(self.workdir, "__ABI_MPIABORTFILE__")) # Directories with input|output|temporary data. self.wdir = Directory(self.workdir) self.indir = Directory(os.path.join(self.workdir, "indata")) self.outdir = Directory(os.path.join(self.workdir, "outdata")) self.tmpdir = Directory(os.path.join(self.workdir, "tmpdata")) # stderr and output file of the queue manager. Note extensions. self.qerr_file = File(os.path.join(self.workdir, "queue.qerr")) self.qout_file = File(os.path.join(self.workdir, "queue.qout"))
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L1378-L1404
set working directory
python
def set_workdir(self, workdir, chroot=False): """ Set the working directory. Cannot be set more than once unless chroot is True """ if not chroot and hasattr(self, "workdir") and self.workdir != workdir: raise ValueError("self.workdir != workdir: %s, %s" % (self.workdir, workdir)) # Directories with (input|output|temporary) data. self.workdir = os.path.abspath(workdir) self.indir = Directory(os.path.join(self.workdir, "indata")) self.outdir = Directory(os.path.join(self.workdir, "outdata")) self.tmpdir = Directory(os.path.join(self.workdir, "tmpdata")) self.wdir = Directory(self.workdir)
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/flows.py#L254-L266
set working directory
python
def set_working_directory(self, path): r""" Set the working directory to ``path``\ . All relative paths will be resolved relative to it. :type path: str :param path: the path of the directory :raises: :exc:`~exceptions.IOError` """ _complain_ifclosed(self.closed) return self.fs.set_working_directory(path)
https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/fs.py#L461-L471
set working directory
python
def working_directory(path): """ A context manager that changes the working directory to the given path, and then changes it back to its previous value on exit. """ prev_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(prev_cwd)
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/context.py#L181-L191
set working directory
python
def __set_workdir(self): """Set current script directory as working directory""" fname = self.get_current_filename() if fname is not None: directory = osp.dirname(osp.abspath(fname)) self.open_dir.emit(directory)
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/plugin.py#L1537-L1542
set working directory
python
def set_working_dir(self, working_dir): """ Sets the working directory for this hypervisor. :param working_dir: path to the working directory """ # encase working_dir in quotes to protect spaces in the path yield from self.send('hypervisor working_dir "{}"'.format(working_dir)) self._working_dir = working_dir log.debug("Working directory set to {}".format(self._working_dir))
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/dynamips_hypervisor.py#L152-L162
set working directory
python
def working_directory(path): """Change working directory and restore the previous on exit""" prev_dir = os.getcwd() os.chdir(str(path)) try: yield finally: os.chdir(prev_dir)
https://github.com/wimglenn/wimpy/blob/4e8ebe4e7052d88c9f88ac7dcaa1b587cc2cf86e/wimpy/util.py#L41-L48
set working directory
python
def working_directory(self): """ Get the current working directory. :rtype: str :return: current working directory """ _complain_ifclosed(self.closed) wd = self.fs.get_working_directory() return wd
https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/fs.py#L483-L492
set working directory
python
def do_set_workdir(self, args): """Set the working directory. The working directory is used to load and save known devices to improve startup times. During startup the application loads and saves a file `insteon_plm_device_info.dat`. This file is saved in the working directory. The working directory has no default value. If the working directory is not set, the `insteon_plm_device_info.dat` file is not loaded or saved. Usage: set_workdir workdir Arguments: workdir: Required - Working directory to load and save devie list """ params = args.split() workdir = None try: workdir = params[0] except IndexError: _LOGGING.error('Device name required.') self.do_help('set_workdir') if workdir: self.tools.workdir = workdir
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/tools.py#L877-L903
set working directory
python
def set_working_directory(working_directory): """Add working_directory to sys.paths. This allows dynamic loading of arbitrary python modules in cwd. Args: working_directory: string. path to add to sys.paths """ logger.debug("starting") logger.debug(f"adding {working_directory} to sys.paths") sys.path.append(working_directory) logger.debug("done")
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/moduleloader.py#L51-L65
set working directory
python
def change_to_workdir(self): """Change working directory to working attribute :return: None """ logger.info("Changing working directory to: %s", self.workdir) self.check_dir(self.workdir) try: os.chdir(self.workdir) except OSError as exp: self.exit_on_error("Error changing to working directory: %s. Error: %s. " "Check the existence of %s and the %s/%s account " "permissions on this directory." % (self.workdir, str(exp), self.workdir, self.user, self.group), exit_code=3) self.pre_log.append(("INFO", "Using working directory: %s" % os.path.abspath(self.workdir)))
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1243-L1259
set working directory
python
def create_working_dir(config, prefix): ''' Create a fresh temporary directory, based on the fiven prefix. Returns the new path. ''' # Fetch base directory from executor configuration basepath = config.get("Execution", "directory") if not prefix: prefix = 'opensubmit' finalpath = tempfile.mkdtemp(prefix=prefix + '_', dir=basepath) if not finalpath.endswith(os.sep): finalpath += os.sep logger.debug("Created fresh working directory at {0}.".format(finalpath)) return finalpath
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/executor/opensubmitexec/filesystem.py#L119-L135
set working directory
python
def working_dir(path): """ Change working directory within a context:: >>> import os >>> from cqparts.utils import working_dir >>> print(os.getcwd()) /home/myuser/temp >>> with working_dir('..'): ... print(os.getcwd()) ... /home/myuser :param path: working path to use while in context :type path: :class:`str` """ initial_path = os.getcwd() os.chdir(path) yield os.chdir(initial_path)
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/misc.py#L62-L83
set working directory
python
def working_directory(self): """ The working_directory property :return: str """ if self.chroot_directory and not \ self._working_directory.startswith(self.chroot_directory): return self.chroot_directory + self._working_directory else: return self._working_directory
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L196-L205
set working directory
python
def set_cwd(self, dirname): """Set shell current working directory.""" # Replace single for double backslashes on Windows if os.name == 'nt': dirname = dirname.replace(u"\\", u"\\\\") if not self.external_kernel: code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code) self._cwd = dirname
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L110-L122
set working directory
python
def _createWorkingDir(rootdir,input): """ Create a working directory based on input name under the parent directory specified as rootdir """ # extract rootname from input rootname = input[:input.find('_')] newdir = os.path.join(rootdir,rootname) if not os.path.exists(newdir): os.mkdir(newdir) return newdir
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L578-L587
set working directory
python
def set_directory(path): """ | Creates a directory with given path. | The directory creation is delegated to Python :func:`os.makedirs` definition so that directories hierarchy is recursively created. :param path: Directory path. :type path: unicode :return: Definition success. :rtype: bool """ try: if not foundations.common.path_exists(path): LOGGER.debug("> Creating directory: '{0}'.".format(path)) os.makedirs(path) return True else: LOGGER.debug("> '{0}' directory already exist, skipping creation!".format(path)) return True except Exception as error: raise foundations.exceptions.DirectoryCreationError( "!> {0} | Cannot create '{1}' directory: '{2}'".format(__name__, path, error))
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/io.py#L292-L314
set working directory
python
def work_dir(path): ''' Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status') ''' starting_directory = os.getcwd() try: os.chdir(path) yield finally: os.chdir(starting_directory)
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L79-L94
set working directory
python
def cd(path, on=os): """Change the current working directory within this context. Preserves the previous working directory and can be applied to remote connections that offer @getcwd@ and @chdir@ methods using the @on@ argument. """ original = on.getcwd() on.chdir(path) yield on.chdir(original)
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/context/__init__.py#L13-L26
set working directory
python
def cd(self, path=None): """ Get or set the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory). Args: path: New working directory or None (to display the working directory). Returns: Current working directory. """ if path is None: return lock_and_call( lambda: self._impl.cd(), self._lock ) else: return lock_and_call( lambda: self._impl.cd(path), self._lock )
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L477-L498
set working directory
python
def set_cwd(fn): """ Decorator to set the specified working directory to execute the function, and then restore the previous cwd. """ def wrapped(self, *args, **kwargs): log.info('Calling function: %s with args=%s', fn, args if args else []) cwd = os.getcwd() log.info('Saved cwd: %s', cwd) os.chdir(self._cwd) log.info('Changing working directory to: %s', self._cwd) try: return fn(self, *args, **kwargs) finally: os.chdir(cwd) log.info('Restored working directory to: %s', cwd) return wrapped
https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L108-L124
set working directory
python
def set_folder(self, folder): """ Sets the folder where the files to serve are located. """ self.folder = folder self.templates.directories[0] = folder self.app.root_path = folder
https://github.com/nicolas-van/pygreen/blob/41d433edb408f86278cf95269fabf3acc00c9119/pygreen.py#L81-L87
set working directory
python
def set_outdir(self): """Set output directory.""" dirname = self.w.outdir.get_text() if os.path.isdir(dirname): self.outdir = dirname self.logger.debug('Output directory set to {0}'.format(self.outdir)) else: self.w.outdir.set_text(self.outdir) self.logger.error('{0} is not a directory'.format(dirname))
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L314-L322
set working directory
python
def get_working_dir(script__file__): """ hardcoded sets the 'equivalent' working directory if not in git """ start = Path(script__file__).resolve() _root = Path(start.root) working_dir = start while not list(working_dir.glob('.git')): if working_dir == _root: return working_dir = working_dir.parent return working_dir
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/utils.py#L23-L34
set working directory
python
def setup_dir(self): """Change directory for script if necessary.""" cd = self.opts.cd or self.config['crony'].get('directory') if cd: self.logger.debug(f'Adding cd to {cd}') self.cmd = f'cd {cd} && {self.cmd}'
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L160-L165
set working directory
python
def cwd(): """Return the be current working directory""" cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L52-L58
set working directory
python
def working_area(files, name=""): """ Copy all files to a temporary directory (the working area) Optionally names the working area name Returns path to the working area """ with tempfile.TemporaryDirectory() as dir: dir = Path(Path(dir) / name) dir.mkdir(exist_ok=True) for f in files: dest = (dir / f).absolute() dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy(f, dest) yield dir
https://github.com/cs50/lib50/blob/941767f6c0a3b81af0cdea48c25c8d5a761086eb/lib50/_api.py#L101-L115
set working directory
python
def cd(directory): """Change the current working directory, temporarily. Use as a context manager: with cd(d): ... """ old_dir = os.getcwd() try: os.chdir(directory) yield finally: os.chdir(old_dir)
https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L164-L174
set working directory
python
def change_dir(self, session, path): """ Changes the working directory """ if path == "-": # Previous directory path = self._previous_path or "." try: previous = os.getcwd() os.chdir(path) except IOError as ex: # Can't change directory session.write_line("Error changing directory: {0}", ex) else: # Store previous path self._previous_path = previous session.write_line(os.getcwd())
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L704-L721
set working directory
python
def preserve_set_th1_add_directory(state=True): """ Context manager to temporarily set TH1.AddDirectory() state """ with LOCK: status = ROOT.TH1.AddDirectoryStatus() try: ROOT.TH1.AddDirectory(state) yield finally: ROOT.TH1.AddDirectory(status)
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/context.py#L167-L177
set working directory
python
def setdirs(outfiles): """Create the directories if need be""" for k in outfiles: fname=outfiles[k] dname= os.path.dirname(fname) if not os.path.isdir(dname): os.mkdir(dname)
https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/convert/convertcases.py#L76-L82
set working directory
python
def step_a_new_working_directory(context): """ Creates a new, empty working directory """ command_util.ensure_context_attribute_exists(context, "workdir", None) command_util.ensure_workdir_exists(context) shutil.rmtree(context.workdir, ignore_errors=True)
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/command_steps.py#L79-L85
set working directory
python
def chdir(directory): """Change the current working directory to a different directory for a code block and return the previous directory after the block exits. Useful to run commands from a specificed directory. :param str directory: The directory path to change to for this context. """ cur = os.getcwd() try: yield os.chdir(directory) finally: os.chdir(cur)
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L883-L894
set working directory
python
def settings_dir(self): """ Directory that contains the the settings for the project """ path = os.path.join(self.dir, '.dsb') utils.create_dir(path) return os.path.realpath(path)
https://github.com/danielfrg/datasciencebox/blob/6b7aa642c6616a46547035fcb815acc1de605a6f/datasciencebox/core/project.py#L58-L64
set working directory
python
def set_cwd(new_path): """ Usage: with set_cwd('/some/dir'): walk_around_the_filesystem() """ try: curdir = os.getcwd() except OSError: curdir = new_path try: os.chdir(new_path) yield finally: os.chdir(curdir)
https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/context.py#L8-L23
set working directory
python
def mkdir(dirs, user=None, group=None, mode=None, use_sudo=True): """Create directory with sudo and octal mode, then set ownership.""" if isinstance(dirs, basestring): dirs = [dirs] runner = sudo if use_sudo else run if dirs: modearg = '-m {:o}'.format(mode) if mode else '' cmd = 'mkdir -v -p {} {}'.format(modearg, ' '.join(dirs)) result = runner(cmd) with hide('commands'): chown(dirs, user, group) return result
https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L112-L123
set working directory
python
def cd(self, *subpaths): """ Change the current working directory and update all the paths in the workspace. This is useful for commands that have to be run from a certain directory. """ target = os.path.join(*subpaths) os.chdir(target)
https://github.com/Kortemme-Lab/pull_into_place/blob/247f303100a612cc90cf31c86e4fe5052eb28c8d/pull_into_place/pipeline.py#L340-L347
set working directory
python
def set_current_client_working_directory(self, directory): """Set current client working directory.""" shellwidget = self.get_current_shellwidget() if shellwidget is not None: shellwidget.set_cwd(directory)
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L571-L575
set working directory
python
def _ensure_dir(directory, description): """ Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created. """ if not os.path.exists(directory): try: os.makedirs(directory) except OSError, e: sys.stderr.write("could not create %s directory %s: %s" % ( description, directory, str(e)))
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/common/run.py#L247-L258
set working directory
python
def as_cwd(): """ Use workdir.options.path as a temporary working directory """ _set_log_level() owd = os.getcwd() logger.debug('entering working directory: ' + options.path) os.chdir(os.path.expanduser(options.path)) yield logger.debug('returning to original directory: ' + owd) os.chdir(owd)
https://github.com/ajk8/workdir-python/blob/44a62f45cefb9a1b834d23191e88340b790a553e/workdir/__init__.py#L38-L46
set working directory
python
def setup_dirs(): """Make required directories to hold logfile. :returns: str """ try: top_dir = os.path.abspath(os.path.expanduser(os.environ["XDG_CACHE_HOME"])) except KeyError: top_dir = os.path.abspath(os.path.expanduser("~/.cache")) our_cache_dir = os.path.join(top_dir, PROJECT_NAME) os.makedirs(our_cache_dir, mode=0o775, exist_ok=True) return our_cache_dir
https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/util.py#L42-L53
set working directory
python
def chdir(path): """Change the working directory to `path` for the duration of this context manager. :param str path: The path to change to """ cur_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(cur_cwd)
https://github.com/naphatkrit/temp-utils/blob/4b0cb5a76fcaa9f3b5db05ed1f5f7a1979a86d2c/temp_utils/contextmanagers.py#L9-L20
set working directory
python
def cd(path): """Context manager to temporarily change working directories :param str path: The directory to move into >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' >>> with cd("/home/user/code/otherdir/subdir"): ... print("Changed directory: %s" % os.path.abspath(os.curdir)) Changed directory: /home/user/code/otherdir/subdir >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' """ if not path: return prev_cwd = Path.cwd().as_posix() if isinstance(path, Path): path = path.as_posix() os.chdir(str(path)) try: yield finally: os.chdir(prev_cwd)
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L63-L85
set working directory
python
def chdir(self, target_directory): """Change current working directory to target directory. Args: target_directory: The path to new current working directory. Raises: OSError: if user lacks permission to enter the argument directory or if the target is not a directory. """ target_directory = self.filesystem.resolve_path( target_directory, allow_fd=True) self.filesystem.confirmdir(target_directory) directory = self.filesystem.resolve(target_directory) # A full implementation would check permissions all the way # up the tree. if not is_root() and not directory.st_mode | PERM_EXE: self.filesystem.raise_os_error(errno.EACCES, directory) self.filesystem.cwd = target_directory
https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3813-L3831
set working directory
python
def get_DIR(self): """ Dialog that allows user to choose a working directory """ dlg = wx.DirDialog(self, "Choose a directory:", defaultPath=self.currentDirectory, style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR) ok = self.show_dlg(dlg) if ok == wx.ID_OK: new_WD = dlg.GetPath() dlg.Destroy() else: new_WD = os.getcwd() dlg.Destroy() return new_WD
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L5093-L5106
set working directory
python
def cd(self, folder): """ Changes the working directory on the server. :param folder: the desired directory. :type folder: string """ if folder.startswith('/'): self._ftp.cwd(folder) else: for subfolder in folder.split('/'): if subfolder: self._ftp.cwd(subfolder)
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L130-L141
set working directory
python
def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) return path
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L358-L368
set working directory
python
def pwd(editor, location): " Change working directory. " try: os.chdir(location) except OSError as e: editor.show_message('{}'.format(e))
https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/commands/commands.py#L412-L417
set working directory
python
def performInDirectory(dirPath): """ Change the current working directory to dirPath before performing an operation, then restore the original working directory after """ originalDirectoryPath = os.getcwd() try: os.chdir(dirPath) yield finally: os.chdir(originalDirectoryPath)
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L339-L349
set working directory
python
def set_workdir(self, workdir, chroot=False): """Set the working directory of the task.""" super().set_workdir(workdir, chroot=chroot) # Small hack: the log file of optics is actually the main output file. self.output_file = self.log_file
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L4149-L4153
set working directory
python
def cd(self, remote): """ Change working directory on server """ try: self.conn.cwd(remote) except Exception: return False else: return self.pwd()
https://github.com/codebynumbers/ftpretty/blob/5ee6e2cc679199ff52d1cd2ed1b0613f12aa6f67/ftpretty.py#L196-L203
set working directory
python
def chdir(self, dir, change_os_dir=0): """Change the current working directory for lookups. If change_os_dir is true, we will also change the "real" cwd to match. """ curr=self._cwd try: if dir is not None: self._cwd = dir if change_os_dir: os.chdir(dir.get_abspath()) except OSError: self._cwd = curr raise
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1168-L1181
set working directory
python
def set_cwd(cls, cwd): """ Set the cwd that is used to manipulate paths. """ if not cwd: try: cwd = os.getcwdu() except AttributeError: cwd = os.getcwd() if isinstance(cwd, six.binary_type): cwd = cwd.decode(sys.getdefaultencoding()) cls._cwd = cwd cls._root = cls._git_root()
https://github.com/Bachmann1234/diff-cover/blob/901cb3fc986982961785e841658085ead453c6c9/diff_cover/git_path.py#L23-L35
set working directory
python
def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """ directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %s failed! Directory does not exist!", directory ) return False os.chdir(directory) return True except Exception as e: logger.error("chdir -> %s failed! %s" % (directory, e)) return False
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L73-L91
set working directory
python
def prepare(self): """ Prepare the Directory for use in an Environment. This will create the directory if the create flag is set. """ if self._create: self.create() for k in self._children: self._children[k]._env = self._env self._children[k].prepare()
https://github.com/snare/scruffy/blob/0fedc08cfdb6db927ff93c09f25f24ce5a04c541/scruffy/file.py#L336-L346
set working directory
python
def Cwd(directory): ''' Context manager for current directory (uses with_statement) e.g.: # working on some directory with Cwd('/home/new_dir'): # working on new_dir # working on some directory again :param unicode directory: Target directory to enter ''' old_directory = six.moves.getcwd() if directory is not None: os.chdir(directory) try: yield directory finally: os.chdir(old_directory)
https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L70-L90
set working directory
python
def ensure_dir (self, mode=0o777, parents=False): """Ensure that this path exists as a directory. This function calls :meth:`mkdir` on this path, but does not raise an exception if it already exists. It does raise an exception if this path exists but is not a directory. If the directory is created, *mode* is used to set the permissions of the resulting directory, with the important caveat that the current :func:`os.umask` is applied. It returns a boolean indicating if the directory was actually created. If *parents* is true, parent directories will be created in the same manner. """ if parents: p = self.parent if p == self: return False # can never create root; avoids loop when parents=True p.ensure_dir (mode, True) made_it = False try: self.mkdir (mode) made_it = True except OSError as e: if e.errno == 17: # EEXIST? return False # that's fine raise # other exceptions are not fine if not self.is_dir (): import errno raise OSError (errno.ENOTDIR, 'Not a directory', str(self)) return made_it
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/io.py#L402-L437
set working directory
python
def chdir(self, directory_path, make=False): """Change directories and optionally make the directory if it doesn't exist.""" if os.sep in directory_path: for directory in directory_path.split(os.sep): if make and not self.directory_exists(directory): try: self.session.mkd(directory) except ftplib.error_perm: # Directory already exists pass self.session.cwd(directory) else: self.session.cwd(directory_path)
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/ftp.py#L81-L93
set working directory
python
def make_dirs(path): """ Create directories if not exist :param path: string :return: """ try: os.makedirs(os.path.dirname(path)) except OSError as err: if err.errno != errno.EEXIST: LOGGER.error('Failed to create directory %s with error: %s' % (path, str(err))) raise
https://github.com/FlaskGuys/Flask-Imagine/blob/f79c6517ecb5480b63a2b3b8554edb6e2ac8be8c/flask_imagine/adapters/filesystem.py#L139-L150
set working directory
python
def makeDirectory(self, full_path, dummy = 40841): """Make a directory >>> nd.makeDirectory('/test') :param full_path: The full path to get the directory property. Should be end with '/'. :return: ``True`` when success to make a directory or ``False`` """ if full_path[-1] is not '/': full_path += '/' data = {'dstresource': full_path, 'userid': self.user_id, 'useridx': self.useridx, 'dummy': dummy, } s, metadata = self.POST('makeDirectory', data) return s
https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/ndrive/client.py#L544-L564
set working directory
python
def make_directory(path): """ Create directory if that not exists. """ try: makedirs(path) logging.debug('Directory created: {0}'.format(path)) except OSError as e: if e.errno != errno.EEXIST: raise
https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L42-L50
set working directory
python
def make_dir(cls, directory_name): """Create a directory in the system""" if not os.path.exists(directory_name): os.makedirs(directory_name)
https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/libs/common.py#L35-L38
set working directory
python
def set_folder(self, folder='assets'): """ Changes the file folder to look at :param folder: str [images, assets] :return: None """ folder = folder.replace('/', '.') self._endpoint = 'files/{folder}'.format(folder=folder)
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/files.py#L10-L18
set working directory
python
def chdir(self, directory, browsing_history=False, refresh_explorer=True, refresh_console=True): """Set directory as working directory""" if directory: directory = osp.abspath(to_text_string(directory)) # Working directory history management if browsing_history: directory = self.history[self.histindex] elif directory in self.history: self.histindex = self.history.index(directory) else: if self.histindex is None: self.history = [] else: self.history = self.history[:self.histindex+1] self.history.append(directory) self.histindex = len(self.history)-1 # Changing working directory try: os.chdir(directory) if refresh_explorer: self.set_explorer_cwd.emit(directory) if refresh_console: self.set_current_console_wd.emit(directory) self.refresh_findinfiles.emit() except OSError: self.history.pop(self.histindex) self.refresh_plugin()
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L211-L240
set working directory
python
def _set_results_dir(self): """Create results directory if not exists.""" if self.running_instance_id: self.results_dir = os.path.join( self.results_dir, self.cloud, self.image_id, self.running_instance_id ) else: self.results_dir = os.path.join( self.results_dir, self.cloud, self.instance_ip ) try: os.makedirs(self.results_dir) except OSError as error: if not os.path.isdir(self.results_dir): raise IpaCloudException( 'Unable to create ipa results directory: %s' % error ) self.time_stamp = datetime.now().strftime('%Y%m%d%H%M%S') self.log_file = ''.join( [self.results_dir, os.sep, self.time_stamp, '.log'] ) self.logger.debug('Created log file %s' % self.log_file) self.results_file = ''.join( [self.results_dir, os.sep, self.time_stamp, '.results'] ) self.logger.debug('Created results file %s' % self.results_file) # Add log file handler file_handler = logging.FileHandler(self.log_file) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter('\n%(message)s\n')) self.logger.addHandler(file_handler)
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L368-L407
set working directory
python
def create(self, segment): """A best-effort attempt to create directories. Warnings are issued to the user if those directories could not created or if they don't exist. The caller should only call this function if the user requested prefetching (i.e. concurrency) to avoid spurious warnings. """ def lackadaisical_mkdir(place): ok = False place = path.realpath(place) try: os.makedirs(place, 0o700) ok = True except EnvironmentError as e: if e.errno == errno.EEXIST: # Has already been created: this is the most # common situation, and is fine. ok = True else: logger.warning( msg='could not create prefetch directory', detail=('Prefetch directory creation target: {0}, {1}' .format(place, e.strerror))) return ok ok = True for d in [self.prefetched_dir, self.running]: ok &= lackadaisical_mkdir(d) lackadaisical_mkdir(self.seg_dir(segment))
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/prefetch.py#L91-L128
set working directory
python
def create(): """ Create workdir.options.path """ if not os.path.isdir(options.path): logger.info('creating working directory: ' + options.path) os.makedirs(options.path)
https://github.com/ajk8/workdir-python/blob/44a62f45cefb9a1b834d23191e88340b790a553e/workdir/__init__.py#L87-L91
set working directory
python
def node_working_directory(self, node): """ Returns a working directory for a specific node. If the directory doesn't exist, the directory is created. :param node: Node instance :returns: Node working directory """ workdir = self.node_working_path(node) if not self._deleted: try: os.makedirs(workdir, exist_ok=True) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create the node working directory: {}".format(e)) return workdir
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L200-L216
set working directory
python
def set_directory(robject): """ Context manager to temporarily set the directory of a ROOT object (if possible) """ if (not hasattr(robject, 'GetDirectory') or not hasattr(robject, 'SetDirectory')): log.warning("Cannot set the directory of a `{0}`".format( type(robject))) # Do nothing yield else: old_dir = robject.GetDirectory() try: robject.SetDirectory(ROOT.gDirectory) yield finally: robject.SetDirectory(old_dir)
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/context.py#L146-L163
set working directory
python
def make_dir(self): """Make the directory where the file is located.""" if not os.path.exists(self.dirname): os.makedirs(self.dirname)
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/utils.py#L124-L127
set working directory
python
def change_directory(path=None): """ Context manager that changes directory and resets it when existing >>> with change_directory('/tmp'): >>> pass """ if path is not None: try: oldpwd = getcwd() logger.debug('changing directory from %s to %s' % (oldpwd, path)) chdir(path) yield finally: chdir(oldpwd) else: yield
https://github.com/devopsconsulting/vdt.version/blob/25854ac9e1a26f1c7d31c26fd012781f05570574/vdt/version/utils.py#L81-L97
set working directory
python
def ensure_dir(self, mode=0777): """ Make sure the directory exists, create if necessary. """ if not self.exists() or not self.isdir(): os.makedirs(self, mode)
https://github.com/olt/scriptine/blob/f4cfea939f2f3ad352b24c5f6410f79e78723d0e/scriptine/_path.py#L914-L919
set working directory
python
def directory(name, user=None, group=None, recurse=None, max_depth=None, dir_mode=None, file_mode=None, makedirs=False, clean=False, require=None, exclude_pat=None, follow_symlinks=False, force=False, backupname=None, allow_symlink=True, children_only=False, win_owner=None, win_perms=None, win_deny_perms=None, win_inheritance=True, win_perms_reset=False, **kwargs): r''' Ensure that a named directory is present and has the right perms name The location to create or manage a directory, as an absolute path user The user to own the directory; this defaults to the user salt is running as on the minion group The group ownership set for the directory; this defaults to the group salt is running as on the minion. On Windows, this is ignored recurse Enforce user/group ownership and mode of directory recursively. Accepts a list of strings representing what you would like to recurse. If ``mode`` is defined, will recurse on both ``file_mode`` and ``dir_mode`` if they are defined. If ``ignore_files`` or ``ignore_dirs`` is included, files or directories will be left unchanged respectively. If ``silent`` is defined, individual file/directory change notifications will be suppressed. Example: .. code-block:: yaml /var/log/httpd: file.directory: - user: root - group: root - dir_mode: 755 - file_mode: 644 - recurse: - user - group - mode Leave files or directories unchanged: .. code-block:: yaml /var/log/httpd: file.directory: - user: root - group: root - dir_mode: 755 - file_mode: 644 - recurse: - user - group - mode - ignore_dirs .. versionadded:: 2015.5.0 max_depth Limit the recursion depth. The default is no limit=None. 'max_depth' and 'clean' are mutually exclusive. .. versionadded:: 2016.11.0 dir_mode / mode The permissions mode to set any directories created. Not supported on Windows. The default mode for new files and directories corresponds umask of salt process. For existing files and directories it's not enforced. file_mode The permissions mode to set any files created if 'mode' is run in 'recurse'. This defaults to dir_mode. Not supported on Windows. The default mode for new files and directories corresponds umask of salt process. For existing files and directories it's not enforced. makedirs If the directory is located in a path without a parent directory, then the state will fail. If makedirs is set to True, then the parent directories will be created to facilitate the creation of the named file. clean Make sure that only files that are set up by salt and required by this function are kept. If this option is set then everything in this directory will be deleted unless it is required. 'clean' and 'max_depth' are mutually exclusive. require Require other resources such as packages or files exclude_pat When 'clean' is set to True, exclude this pattern from removal list and preserve in the destination. follow_symlinks : False If the desired path is a symlink (or ``recurse`` is defined and a symlink is encountered while recursing), follow it and check the permissions of the directory/file to which the symlink points. .. versionadded:: 2014.1.4 force If the name of the directory exists and is not a directory and force is set to False, the state will fail. If force is set to True, the file in the way of the directory will be deleted to make room for the directory, unless backupname is set, then it will be renamed. .. versionadded:: 2014.7.0 backupname If the name of the directory exists and is not a directory, it will be renamed to the backupname. If the backupname already exists and force is False, the state will fail. Otherwise, the backupname will be removed first. .. versionadded:: 2014.7.0 allow_symlink : True If allow_symlink is True and the specified path is a symlink, it will be allowed to remain if it points to a directory. If allow_symlink is False then the state will fail, unless force is also set to True, in which case it will be removed or renamed, depending on the value of the backupname argument. .. versionadded:: 2014.7.0 children_only : False If children_only is True the base of a path is excluded when performing a recursive operation. In case of /path/to/base, base will be ignored while all of /path/to/base/* are still operated on. win_owner : None The owner of the directory. If this is not passed, user will be used. If user is not passed, the account under which Salt is running will be used. .. versionadded:: 2017.7.0 win_perms : None A dictionary containing permissions to grant and their propagation. For example: ``{'Administrators': {'perms': 'full_control', 'applies_to': 'this_folder_only'}}`` Can be a single basic perm or a list of advanced perms. ``perms`` must be specified. ``applies_to`` is optional and defaults to ``this_folder_subfolder_files``. .. versionadded:: 2017.7.0 win_deny_perms : None A dictionary containing permissions to deny and their propagation. For example: ``{'Administrators': {'perms': 'full_control', 'applies_to': 'this_folder_only'}}`` Can be a single basic perm or a list of advanced perms. .. versionadded:: 2017.7.0 win_inheritance : True True to inherit permissions from the parent directory, False not to inherit permission. .. versionadded:: 2017.7.0 win_perms_reset : False If ``True`` the existing DACL will be cleared and replaced with the settings defined in this function. If ``False``, new entries will be appended to the existing DACL. Default is ``False``. .. versionadded:: 2018.3.0 Here's an example using the above ``win_*`` parameters: .. code-block:: yaml create_config_dir: file.directory: - name: 'C:\config\' - win_owner: Administrators - win_perms: # Basic Permissions dev_ops: perms: full_control # List of advanced permissions appuser: perms: - read_attributes - read_ea - create_folders - read_permissions applies_to: this_folder_only joe_snuffy: perms: read applies_to: this_folder_files - win_deny_perms: fred_snuffy: perms: full_control - win_inheritance: False ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not name: return _error(ret, 'Must provide name to file.directory') # Remove trailing slash, if present and we're not working on "/" itself if name[-1] == '/' and name != '/': name = name[:-1] if max_depth is not None and clean: return _error(ret, 'Cannot specify both max_depth and clean') user = _test_owner(kwargs, user=user) if salt.utils.platform.is_windows(): # If win_owner not passed, use user if win_owner is None: win_owner = user if user else salt.utils.win_functions.get_current_user() # Group isn't relevant to Windows, use win_perms/win_deny_perms if group is not None: log.warning( 'The group argument for %s has been ignored as this is ' 'a Windows system. Please use the `win_*` parameters to set ' 'permissions in Windows.', name ) group = user if 'mode' in kwargs and not dir_mode: dir_mode = kwargs.get('mode', []) if not file_mode: file_mode = dir_mode # Make sure that leading zeros stripped by YAML loader are added back dir_mode = salt.utils.files.normalize_mode(dir_mode) file_mode = salt.utils.files.normalize_mode(file_mode) if salt.utils.platform.is_windows(): # Verify win_owner is valid on the target system try: salt.utils.win_dacl.get_sid(win_owner) except CommandExecutionError as exc: return _error(ret, exc) else: # Verify user and group are valid u_check = _check_user(user, group) if u_check: # The specified user or group do not exist return _error(ret, u_check) # Must be an absolute path if not os.path.isabs(name): return _error( ret, 'Specified file {0} is not an absolute path'.format(name)) # Check for existing file or symlink if os.path.isfile(name) or (not allow_symlink and os.path.islink(name)) \ or (force and os.path.islink(name)): # Was a backupname specified if backupname is not None: # Make a backup first if os.path.lexists(backupname): if not force: return _error(ret, (( 'File exists where the backup target {0} should go' ).format(backupname))) else: __salt__['file.remove'](backupname) os.rename(name, backupname) elif force: # Remove whatever is in the way if os.path.isfile(name): if __opts__['test']: ret['changes']['forced'] = 'File would be forcibly replaced' else: os.remove(name) ret['changes']['forced'] = 'File was forcibly replaced' elif __salt__['file.is_link'](name): if __opts__['test']: ret['changes']['forced'] = 'Symlink would be forcibly replaced' else: __salt__['file.remove'](name) ret['changes']['forced'] = 'Symlink was forcibly replaced' else: if __opts__['test']: ret['changes']['forced'] = 'Directory would be forcibly replaced' else: __salt__['file.remove'](name) ret['changes']['forced'] = 'Directory was forcibly replaced' else: if os.path.isfile(name): return _error( ret, 'Specified location {0} exists and is a file'.format(name)) elif os.path.islink(name): return _error( ret, 'Specified location {0} exists and is a symlink'.format(name)) # Check directory? if salt.utils.platform.is_windows(): presult, pcomment, pchanges = _check_directory_win( name=name, win_owner=win_owner, win_perms=win_perms, win_deny_perms=win_deny_perms, win_inheritance=win_inheritance, win_perms_reset=win_perms_reset) else: presult, pcomment, pchanges = _check_directory( name, user, group, recurse or [], dir_mode, file_mode, clean, require, exclude_pat, max_depth, follow_symlinks, children_only) if pchanges: ret['changes'].update(pchanges) # Don't run through the reset of the function if there are no changes to be # made if __opts__['test'] or not ret['changes']: ret['result'] = presult ret['comment'] = pcomment return ret if not os.path.isdir(name): # The dir does not exist, make it if not os.path.isdir(os.path.dirname(name)): # The parent directory does not exist, create them if makedirs: # Everything's good, create the parent Dirs try: _makedirs(name=name, user=user, group=group, dir_mode=dir_mode, win_owner=win_owner, win_perms=win_perms, win_deny_perms=win_deny_perms, win_inheritance=win_inheritance) except CommandExecutionError as exc: return _error(ret, 'Drive {0} is not mapped'.format(exc.message)) else: return _error( ret, 'No directory to create {0} in'.format(name)) if salt.utils.platform.is_windows(): __salt__['file.mkdir']( path=name, owner=win_owner, grant_perms=win_perms, deny_perms=win_deny_perms, inheritance=win_inheritance, reset=win_perms_reset) else: __salt__['file.mkdir'](name, user=user, group=group, mode=dir_mode) ret['changes'][name] = 'New Dir' if not os.path.isdir(name): return _error(ret, 'Failed to create directory {0}'.format(name)) # issue 32707: skip this __salt__['file.check_perms'] call if children_only == True # Check permissions if not children_only: if salt.utils.platform.is_windows(): ret = __salt__['file.check_perms']( path=name, ret=ret, owner=win_owner, grant_perms=win_perms, deny_perms=win_deny_perms, inheritance=win_inheritance, reset=win_perms_reset) else: ret, perms = __salt__['file.check_perms']( name, ret, user, group, dir_mode, None, follow_symlinks) errors = [] if recurse or clean: # walk path only once and store the result walk_l = list(_depth_limited_walk(name, max_depth)) # root: (dirs, files) structure, compatible for python2.6 walk_d = {} for i in walk_l: walk_d[i[0]] = (i[1], i[2]) recurse_set = None if recurse: try: recurse_set = _get_recurse_set(recurse) except (TypeError, ValueError) as exc: ret['result'] = False ret['comment'] = '{0}'.format(exc) # NOTE: Should this be enough to stop the whole check altogether? if recurse_set: if 'user' in recurse_set: if user or isinstance(user, int): uid = __salt__['file.user_to_uid'](user) # file.user_to_uid returns '' if user does not exist. Above # check for user is not fatal, so we need to be sure user # exists. if isinstance(uid, six.string_types): ret['result'] = False ret['comment'] = 'Failed to enforce ownership for ' \ 'user {0} (user does not ' \ 'exist)'.format(user) else: ret['result'] = False ret['comment'] = 'user not specified, but configured as ' \ 'a target for recursive ownership ' \ 'management' else: user = None if 'group' in recurse_set: if group or isinstance(group, int): gid = __salt__['file.group_to_gid'](group) # As above with user, we need to make sure group exists. if isinstance(gid, six.string_types): ret['result'] = False ret['comment'] = 'Failed to enforce group ownership ' \ 'for group {0}'.format(group) else: ret['result'] = False ret['comment'] = 'group not specified, but configured ' \ 'as a target for recursive ownership ' \ 'management' else: group = None if 'mode' not in recurse_set: file_mode = None dir_mode = None if 'silent' in recurse_set: ret['changes'] = 'Changes silenced' check_files = 'ignore_files' not in recurse_set check_dirs = 'ignore_dirs' not in recurse_set for root, dirs, files in walk_l: if check_files: for fn_ in files: full = os.path.join(root, fn_) try: if salt.utils.platform.is_windows(): ret = __salt__['file.check_perms']( path=full, ret=ret, owner=win_owner, grant_perms=win_perms, deny_perms=win_deny_perms, inheritance=win_inheritance, reset=win_perms_reset) else: ret, _ = __salt__['file.check_perms']( full, ret, user, group, file_mode, None, follow_symlinks) except CommandExecutionError as exc: if not exc.strerror.startswith('Path not found'): errors.append(exc.strerror) if check_dirs: for dir_ in dirs: full = os.path.join(root, dir_) try: if salt.utils.platform.is_windows(): ret = __salt__['file.check_perms']( path=full, ret=ret, owner=win_owner, grant_perms=win_perms, deny_perms=win_deny_perms, inheritance=win_inheritance, reset=win_perms_reset) else: ret, _ = __salt__['file.check_perms']( full, ret, user, group, dir_mode, None, follow_symlinks) except CommandExecutionError as exc: if not exc.strerror.startswith('Path not found'): errors.append(exc.strerror) if clean: keep = _gen_keep_files(name, require, walk_d) log.debug('List of kept files when use file.directory with clean: %s', keep) removed = _clean_dir(name, list(keep), exclude_pat) if removed: ret['changes']['removed'] = removed ret['comment'] = 'Files cleaned from directory {0}'.format(name) # issue 32707: reflect children_only selection in comments if not ret['comment']: if children_only: ret['comment'] = 'Directory {0}/* updated'.format(name) else: if ret['changes']: ret['comment'] = 'Directory {0} updated'.format(name) if __opts__['test']: ret['comment'] = 'Directory {0} not updated'.format(name) elif not ret['changes'] and ret['result']: orig_comment = None if ret['comment']: orig_comment = ret['comment'] ret['comment'] = 'Directory {0} is in the correct state'.format(name) if orig_comment: ret['comment'] = '\n'.join([ret['comment'], orig_comment]) if errors: ret['result'] = False ret['comment'] += '\n\nThe following errors were encountered:\n' for error in errors: ret['comment'] += '\n- {0}'.format(error) return ret
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L3104-L3638
set working directory
python
def do_cd(self, path = '/'): """change current working directory""" path = path[0] if path == "..": self.current_path = "/".join(self.current_path[:-1].split("/")[0:-1]) + '/' elif path == '/': self.current_path = "/" else: if path[-1] == '/': self.current_path += path else: self.current_path += path + '/' resp = self.n.getList(self.current_path, type=3) if resp: self.dirs = [] self.files = [] for f in resp: name = f['href'].encode('utf-8') if name[-1] == '/': self.dirs.append(os.path.basename(name[:-1])) else: self.files.append(os.path.basename(name)) self.prompt = "> %s@Ndrive:%s " %(self.id, self.current_path)
https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L84-L112
set working directory
python
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None): """ Creates output_dir, work_dir, and sets up log """ output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), 'output_dir') debug('Saving results into ' + output_dir) work_dir = safe_mkdir(work_dir or join(output_dir, 'work'), 'working directory') info('Using work directory ' + work_dir) log_fpath = set_up_log(log_dir or safe_mkdir(join(work_dir, 'log')), proc_name + '.log') return output_dir, work_dir, log_fpath
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/proc_args.py#L112-L123
set working directory
python
def pushd(directory): """Change working directories in style and stay organized! :param directory: Where do you want to go and remember? :return: saved directory stack """ directory = os.path.expanduser(directory) _saved_paths.insert(0, os.path.abspath(os.getcwd())) os.chdir(directory) return [directory] + _saved_paths
https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L47-L56
set working directory
python
def make_directory(directory): """ Makes directory if it does not exist. Parameters ----------- directory : :obj:`str` Directory path """ if not os.path.isdir(directory): os.mkdir(directory) logger.info('Path {} not found, I will create it.' .format(directory))
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/tools/config.py#L171-L184
set working directory
python
def make(self): """ Creates this directory and any of the missing directories in the path. Any errors that may occur are eaten. """ try: if not self.exists: logger.info("Creating %s" % self.path) os.makedirs(self.path) except os.error: pass return self
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L549-L560
set working directory
python
def create_dir(path): """ Create directory specified by `path` if it doesn't already exist. Parameters ---------- path : str path to directory Returns ------- bool True if `path` exists """ # https://stackoverflow.com/a/5032238 try: os.makedirs(path, exist_ok=True) except Exception as err: print(err) return False if os.path.exists(path): return True else: return False
https://github.com/apriha/lineage/blob/13106a62a959a80ac26c68d1566422de08aa877b/src/lineage/__init__.py#L859-L882
set working directory
python
def mkdir(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True, reset=False): ''' Ensure that the directory is available and permissions are set. Args: path (str): The full path to the directory. owner (str): The owner of the directory. If not passed, it will be the account that created the directory, likely SYSTEM grant_perms (dict): A dictionary containing the user/group and the basic permissions to grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also set the ``applies_to`` setting here. The default is ``this_folder_subfolders_files``. Specify another ``applies_to`` setting like this: .. code-block:: yaml {'user': {'perms': 'full_control', 'applies_to': 'this_folder'}} To set advanced permissions use a list for the ``perms`` parameter, ie: .. code-block:: yaml {'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}} deny_perms (dict): A dictionary containing the user/group and permissions to deny along with the ``applies_to`` setting. Use the same format used for the ``grant_perms`` parameter. Remember, deny permissions supersede grant permissions. inheritance (bool): If True the object will inherit permissions from the parent, if ``False``, inheritance will be disabled. Inheritance setting will not apply to parent directories if they must be created. reset (bool): If ``True`` the existing DACL will be cleared and replaced with the settings defined in this function. If ``False``, new entries will be appended to the existing DACL. Default is ``False``. .. versionadded:: 2018.3.0 Returns: bool: True if successful Raises: CommandExecutionError: If unsuccessful CLI Example: .. code-block:: bash # To grant the 'Users' group 'read & execute' permissions. salt '*' file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}" # Locally using salt call salt-call file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}" # Specify advanced attributes with a list salt '*' file.mkdir C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}" ''' # Make sure the drive is valid drive = os.path.splitdrive(path)[0] if not os.path.isdir(drive): raise CommandExecutionError('Drive {0} is not mapped'.format(drive)) path = os.path.expanduser(path) path = os.path.expandvars(path) if not os.path.isdir(path): try: # Make the directory os.mkdir(path) # Set owner if owner: salt.utils.win_dacl.set_owner(obj_name=path, principal=owner) # Set permissions set_perms( path=path, grant_perms=grant_perms, deny_perms=deny_perms, inheritance=inheritance, reset=reset) except WindowsError as exc: raise CommandExecutionError(exc) return True
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1230-L1332
set working directory
python
def set_local_path(directory, create_dir=False): """ sets path for local saving of information if create is true we will create the folder even if it doesnt exist """ if not os.path.exists(directory) and create_dir is True: os.makedirs(directory) if not os.path.exists(directory) and create_dir is False: raise AttributeError("Path '%s' does not exist, to make it pass create_dir=True to rinocloud.set_local_path" % directory) if os.path.isdir(directory): rinocloud.path = directory return directory
https://github.com/rinocloud/rinocloud-python/blob/7c4bf994a518f961cffedb7260fc1e4fa1838b38/rinocloud/config.py#L6-L20
set working directory
python
def set_server_dir(self, dir): """ Set the directory of the server to be controlled """ self.dir = os.path.abspath(dir) config = os.path.join(self.dir, 'etc', 'grid', 'config.xml') self.configured = os.path.exists(config)
https://github.com/ome/omego/blob/2dadbf3c6342b6c995f9e0dceaf3c0b7fab030fb/omego/external.py#L55-L61
set working directory
python
def make_dir(self, path, relative=False): """ Make a directory. Args: path (str): Path or URL. relative (bool): Path is relative to current root. """ if not relative: path = self.relpath(path) self._make_dir(self.get_client_kwargs(self.ensure_dir_path( path, relative=True)))
https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L489-L500
set working directory
python
def mkdir(path, owner='root', group='root', perms=0o555, force=False): """Create a directory""" log("Making dir {} {}:{} {:o}".format(path, owner, group, perms)) uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid realpath = os.path.abspath(path) path_exists = os.path.exists(realpath) if path_exists and force: if not os.path.isdir(realpath): log("Removing non-directory file {} prior to mkdir()".format(path)) os.unlink(realpath) os.makedirs(realpath, perms) elif not path_exists: os.makedirs(realpath, perms) os.chown(realpath, uid, gid) os.chmod(realpath, perms)
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L517-L533
set working directory
python
def get_DIR(self, WD=None): """ open dialog box for choosing a working directory """ if "-WD" in sys.argv and FIRST_RUN: ind = sys.argv.index('-WD') self.WD = sys.argv[ind + 1] elif not WD: # if no arg was passed in for WD, make a dialog to choose one dialog = wx.DirDialog(None, "Choose a directory:", defaultPath=self.currentDirectory, style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR) ok = self.show_dlg(dialog) if ok == wx.ID_OK: self.WD = dialog.GetPath() else: self.WD = os.getcwd() dialog.Destroy() self.WD = os.path.realpath(self.WD) # name measurement file if self.data_model == 3: meas_file = 'measurements.txt' else: meas_file = 'magic_measurements.txt' self.magic_file = os.path.join(self.WD, meas_file) # intialize GUI_log self.GUI_log = open(os.path.join(self.WD, "thellier_GUI.log"), 'w+') self.GUI_log.write("starting...\n") self.GUI_log.close() self.GUI_log = open(os.path.join(self.WD, "thellier_GUI.log"), 'a') os.chdir(self.WD) self.WD = os.getcwd()
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L465-L495
set working directory
python
def do_work(self): """ Do work """ self._starttime = time.time() if not os.path.isdir(self._dir2): if self._maketarget: if self._verbose: self.log('Creating directory %s' % self._dir2) try: os.makedirs(self._dir2) self._numnewdirs += 1 except Exception as e: self.log(str(e)) return None # All right! self._mainfunc() self._endtime = time.time()
https://github.com/tkhyn/dirsync/blob/a461a6c31a4cf521c1b6a8bcfcd8602e6288e8ce/dirsync/syncer.py#L183-L201
set working directory
python
def mkdir(self, path, mode=o777): """ Create a folder (directory) named ``path`` with numeric mode ``mode``. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. :param str path: name of the folder to create :param int mode: permissions (posix-style) for the newly-created folder """ path = self._adjust_cwd(path) self._log(DEBUG, "mkdir({!r}, {!r})".format(path, mode)) attr = SFTPAttributes() attr.st_mode = mode self._request(CMD_MKDIR, path, attr)
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L447-L460
set working directory
python
def make_directories(self): """ Checks if required directories exist and creates them if needed. """ if os.path.isdir(self.workdir) == False: os.mkdir(self.workdir)
https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/models.py#L36-L40
set working directory
python
def change_directory(self, directory): """ Changes the current directory. Change is made by running a "cd" command followed by a "clear" command. :param directory: :return: """ self._process.write(('cd %s\n' % directory).encode()) if sys.platform == 'win32': self._process.write((os.path.splitdrive(directory)[0] + '\r\n').encode()) self.clear() else: self._process.write(b'\x0C')
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/terminal.py#L49-L62
set working directory
python
def mkdirs(path, mode): """ Creates the directory specified by path, creating intermediate directories as necessary. If directory already exists, this is a no-op. :param path: The directory to create :type path: str :param mode: The mode to give to the directory e.g. 0o755, ignores umask :type mode: int """ try: o_umask = os.umask(0) os.makedirs(path, mode) except OSError: if not os.path.isdir(path): raise finally: os.umask(o_umask)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/file.py#L42-L59
set working directory
python
def ensure_dir_exists(directory): "Creates local directories if they don't exist." if directory.startswith('gs://'): return if not os.path.exists(directory): dbg("Making dir {}".format(directory)) os.makedirs(directory, exist_ok=True)
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L32-L38
set working directory
python
def make_directory(path): """ Make a directory and any intermediate directories that don't already exist. This function handles the case where two threads try to create a directory at once. """ if not os.path.exists(path): # concurrent writes that try to create the same dir can fail try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST: pass else: raise e
https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/clients/system.py#L71-L86
set working directory
python
def create_directory(self, path, mode=777): """ Creates a directory on the remote system. :param path: full path to the remote directory to create :type path: str :param mode: int representation of octal mode for directory """ conn = self.get_conn() conn.mkdir(path, mode)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sftp_hook.py#L155-L163
set working directory
python
def create_dir(directory): """Create given directory, if doesn't exist. Parameters ---------- directory : string Directory path (can be relative or absolute) Returns ------- string Absolute directory path """ if not os.access(directory, os.F_OK): os.makedirs(directory) return os.path.abspath(directory)
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/__init__.py#L1212-L1227
set working directory
python
def set_dir(self, dir_): """Sets directory, auto-loads, updates all GUI contents.""" self.__lock_set_dir(dir_) self.__lock_auto_load() self.__lock_update_table() self.__update_info() self.__update_window_title()
https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/gui/a_XExplorer.py#L320-L327
set working directory
python
def cd(self, dir_p): """Change the current directory level. in dir_p of type str The name of the directory to go in. return progress of type :class:`IProgress` Progress object to track the operation completion. """ if not isinstance(dir_p, basestring): raise TypeError("dir_p can only be an instance of type basestring") progress = self._call("cd", in_p=[dir_p]) progress = IProgress(progress) return progress
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L8736-L8751
set working directory
python
def git_working_dir(func): """Decorator which changes the current working dir to the one of the git repository in order to assure relative paths are handled correctly""" @wraps(func) def set_git_working_dir(self, *args, **kwargs): cur_wd = os.getcwd() os.chdir(self.repo.working_tree_dir) try: return func(self, *args, **kwargs) finally: os.chdir(cur_wd) # END handle working dir # END wrapper return set_git_working_dir
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/index/util.py#L82-L97
set working directory
python
def cd(self, newdir): """ go to the path """ prevdir = os.getcwd() os.chdir(newdir) try: yield finally: os.chdir(prevdir)
https://github.com/chairco/pyRscript/blob/e952f450a873de52baa4fe80ed901f0cf990c0b7/pyRscript/pyRscript.py#L52-L61