Python os.W_OK Examples

The following are 30 code examples of os.W_OK(). 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 also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: cache.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def GetCacheDir(session):
    """Returns the path of a usable cache directory."""
    cache_dir = session.GetParameter("cache_dir")
    if cache_dir == None:
        return cache_dir

    cache_dir = os.path.expandvars(cache_dir)

    if not cache_dir:
        raise io_manager.IOManagerError(
            "Local profile cache is not configured - "
            "add a cache_dir parameter to ~/.rekallrc.")

    # Cache dir may be specified relative to the home directory.
    cache_dir = os.path.join(config.GetHomeDir(session), cache_dir)

    if not os.access(cache_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK):
        try:
            os.makedirs(cache_dir)
        except (IOError, OSError):
            raise io_manager.IOManagerError(
                "Unable to create or access cache directory %s" % cache_dir)

    return cache_dir 
Example #2
Source File: bulkloader.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def CheckOutputFile(filename):
  """Check that the given file does not exist and can be opened for writing.

  Args:
    filename: The name of the file.

  Raises:
    FileExistsError: if the given filename is not found
    FileNotWritableError: if the given filename is not readable.
    """
  full_path = os.path.abspath(filename)
  if os.path.exists(full_path):
    raise FileExistsError('%s: output file exists' % filename)
  elif not os.access(os.path.dirname(full_path), os.W_OK):
    raise FileNotWritableError(
        '%s: not writable' % os.path.dirname(full_path)) 
Example #3
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def chkdir(self, path):
        """Create folder if nonexistent, check for write permission then change into directory"""
        try:
            os.makedirs(path)
            self.show_message(_("Folder created."))
            self.workdir(path)
            return True
        except OSError as exception:
            if exception.errno == errno.EEXIST:
                self.show_message(_("Directory already exists. OK."))
                if os.access(path, os.W_OK):
                    self.workdir(path)
                else:
                    self.show_message(_("Error: no write permission"))
                    self.workdir(self.stdir)
                return True
            elif exception.errno == errno.EACCES:
                self.show_message(_("Permission denied."))
                return False
            else:
                self.show_message(_("Invalid path"))
                self.workdir(self.stdir)
                return True

    # Verzeichnis wechseln 
Example #4
Source File: project.py    From codimension with GNU General Public License v3.0 6 votes vote down vote up
def saveProject(self):
        """Writes all the settings into the file"""
        if not self.isLoaded():
            return

        # It could be another user project file without write permissions
        skipProjectFile = False
        if exists(self.fileName):
            if not os.access(self.fileName, os.W_OK):
                skipProjectFile = True
        else:
            if not os.access(dirname(self.fileName), os.W_OK):
                skipProjectFile = True

        if not skipProjectFile:
            with open(self.fileName, 'w',
                      encoding=DEFAULT_ENCODING) as diskfile:
                json.dump(self.props, diskfile, indent=4)
        else:
            logging.warning('Skipping updates in %s due to writing permissions',
                            self.fileName) 
Example #5
Source File: filesystem.py    From python-netsurv with MIT License 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example #6
Source File: filesystem.py    From python-netsurv with MIT License 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example #7
Source File: solvers.py    From MatchingMarkets.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setTmpDir(self):
        """Set the tmpDir attribute to a reasonnable location for a temporary
        directory"""
        if os.name != 'nt':
            # On unix use /tmp by default
            self.tmpDir = os.environ.get("TMPDIR", "/tmp")
            self.tmpDir = os.environ.get("TMP", self.tmpDir)
        else:
            # On Windows use the current directory
            self.tmpDir = os.environ.get("TMPDIR", "")
            self.tmpDir = os.environ.get("TMP", self.tmpDir)
            self.tmpDir = os.environ.get("TEMP", self.tmpDir)
        if not os.path.isdir(self.tmpDir):
            self.tmpDir = ""
        elif not os.access(self.tmpDir, os.F_OK + os.W_OK):
            self.tmpDir = "" 
Example #8
Source File: filesystem.py    From recruit with Apache License 2.0 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example #9
Source File: util.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def check_msr():
    """
        Checks if the msr driver is loaded and if the user executing
        benchexec has the read and write permissions for msr.
    """
    res = {"loaded": False, "write": False, "read": False}
    loaded_modules = subprocess.check_output(["lsmod"]).decode("utf-8").split("\n")

    if any("msr" in module for module in loaded_modules):
        res["loaded"] = True
    if res["loaded"]:
        cpu_dirs = os.listdir("/dev/cpu")
        cpu_dirs.remove("microcode")
        if all(os.access("/dev/cpu/{}/msr".format(cpu), os.R_OK) for cpu in cpu_dirs):
            res["read"] = True
        if all(os.access("/dev/cpu/{}/msr".format(cpu), os.W_OK) for cpu in cpu_dirs):
            res["write"] = True
    return res 
Example #10
Source File: __init__.py    From LGWebOSRemote with MIT License 6 votes vote down vote up
def find_config():
    w = None
    for f in search_config:
        f = os.path.expanduser(f)
        f = os.path.abspath(f)
        d = os.path.dirname(f)
        if os.path.exists(d):
            if os.access(d, os.W_OK):
                w = f
            if os.path.exists(f):
                if os.access(f, os.W_OK):
                    return f
        elif os.access(os.path.dirname(d), os.W_OK):
            os.makedirs(d)
            w = f
    if w is None:
        print ("Cannot find suitable config path to write, create one in %s" % ' or '.join(search_config))
        raise Exception("No config file")
    return w 
Example #11
Source File: ciftify_vol_result.py    From ciftify with MIT License 6 votes vote down vote up
def get_output_filename(self, user_outputname):
        '''
        check that we have permissions to write to output directory
        adds 'dscalar.nii' to end of outputname if not already present
        '''
        outputname = os.path.realpath(user_outputname)
        output_dir = os.path.dirname(outputname)
        if not os.access(output_dir, os.W_OK):
            logger.error('Cannot write to output file {}\n'\
                         'The folder does not exist, or you do not have permission to write there'\
                         ''.format(outputname))
            sys.exit(1)
        if not outputname.endswith('dscalar.nii'):
            if not outputname.endswith('dtseries.nii'):
                logger.info("Appending '.dscalar.nii' extension to outputname")
                outputname = '{}.dscalar.nii'.format(outputname)
        return outputname 
Example #12
Source File: tempfile.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _mkstemp_inner(dir, pre, suf, flags):
    """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""

    names = _get_candidate_names()

    for seq in xrange(TMP_MAX):
        name = names.next()
        file = _os.path.join(dir, pre + name + suf)
        try:
            fd = _os.open(file, flags, 0600)
            _set_cloexec(fd)
            return (fd, _os.path.abspath(file))
        except OSError, e:
            if e.errno == _errno.EEXIST:
                continue # try again
            if (_os.name == 'nt' and e.errno == _errno.EACCES and
                _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
                # On windows, when a directory with the chosen name already
                # exists, EACCES error code is returned instead of EEXIST.
                continue
            raise 
Example #13
Source File: Forecaster.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, n_pop=4, **specs):
        
        FortneyMarleyCahoyMix1.__init__(self, **specs)
        
        # number of category
        self.n_pop = int(n_pop)
        
        # read forecaster parameter file
        downloadsdir = get_downloads_dir()
        filename = 'fitting_parameters.h5'
        parampath = os.path.join(downloadsdir, filename)
        if not os.path.exists(parampath) and os.access(downloadsdir, os.W_OK|os.X_OK):
            fitting_url = 'https://raw.github.com/dsavransky/forecaster/master/fitting_parameters.h5'
            self.vprint("Fetching Forecaster fitting parameters from %s to %s" % (fitting_url, parampath))
            try:
                urlretrieve(fitting_url, parampath)
            except:
                self.vprint("Error: Remote fetch failed. Fetch manually or see install instructions.")

        assert os.path.exists(parampath), 'fitting_parameters.h5 must exist in /.EXOSIMS/downloads'

        h5 = h5py.File(parampath, 'r')
        self.all_hyper = h5['hyper_posterior'][:]
        h5.close() 
Example #14
Source File: filesystem.py    From jbox with MIT License 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example #15
Source File: downloader.py    From PickTrue with MIT License 6 votes vote down vote up
def start_download(self):
        self.url.assert_no_error()
        self.save_path.assert_no_error()
        self.proxy.assert_no_error()

        url = self.url.get_input()
        path_prefix = self.save_path.get_path()
        proxy = self.proxy.get_input()

        if not os.access(path_prefix, os.W_OK):
            return info("对下载文件夹没有写权限,请重新选择")
        if self.downloader is not None:
            if not self.downloader.done:
                return info("请停止后再重新点击下载...")
        self.downloader = self.run(
            url=url,
            path_prefix=path_prefix,
            proxy=proxy,
        ) 
Example #16
Source File: downloader.py    From PickTrue with MIT License 6 votes vote down vote up
def start_download(self):
        self.url.assert_no_error()
        self.username.assert_no_error()
        self.password.assert_no_error()
        self.proxy.assert_no_error()
        self.save_path.assert_no_error()

        url = self.url.get_input()
        proxy = self.proxy.get_input() or None
        username = self.username.get_input()
        password = self.password.get_input()
        path_prefix = self.save_path.get_path()

        if not os.access(path_prefix, os.W_OK):
            return info("对下载文件夹没有写权限,请重新选择")
        if self.downloader is not None:
            if not self.downloader.done:
                return info("请停止后再重新点击下载...")
        self.downloader = pixiv_run(
            url=url,
            username=username,
            password=password,
            proxy=proxy,
            path_prefix=path_prefix,
        ) 
Example #17
Source File: fs_utilities.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _test_mode(st_mode, mode, ir_flag, iw_flag, ix_flag):
	test_flags = 0
	if mode & os.R_OK:
		test_flags |= ir_flag
	if mode & os.W_OK:
		test_flags |= iw_flag
	if mode & os.X_OK:
		test_flags |= ix_flag
	return (st_mode & test_flags) == test_flags 
Example #18
Source File: cmd.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def print_repolist(rlist):
    tbl = TextTable("%name %path %writable")

    for r in rlist:
        if os.path.exists(r.path):
            writable = str(bool(os.access(r.path, os.W_OK)))
        else:
            writable = 'N/A'
        tbl.append({'name': r.name,
                    'path': r.path,
                    'writable': writable})

    print tbl 
Example #19
Source File: application.py    From exaddos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def savepid (location):
	if not location:
		return

	ownid = os.getpid()

	flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
	mode = ((os.R_OK | os.W_OK) << 6) | (os.R_OK << 3) | os.R_OK

	try:
		fd = os.open(location,flags,mode)
	except OSError:
		err("PIDfile already exists, not updated %s" % location)
		return False

	try:
		f = os.fdopen(fd,'w')
		line = "%d\n" % ownid
		f.write(line)
		f.close()
	except IOError:
		err("Can not create PIDfile %s" % location)
		return False
	log("Created PIDfile %s with value %d" % (location,ownid))
	atexit.register(removepid,location)
	return True 
Example #20
Source File: config.py    From cf-mendix-buildpack with Apache License 2.0 5 votes vote down vote up
def get_first_writable_mxjar_repo(self):
        repos = self._conf["mxnode"]["mxjar_repo"]
        logger.debug("Searching for writeable mxjar repos... in %s" % repos)
        repos = [repo for repo in repos if os.access(repo, os.W_OK)]
        if len(repos) > 0:
            found = repos[0]
            logger.debug("Found writable mxjar location: %s" % found)
            return found
        else:
            logger.debug("No writable mxjar location found")
            return None 
Example #21
Source File: tempfile.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def mkdtemp(suffix="", prefix=template, dir=None):
    """User-callable function to create and return a unique temporary
    directory.  The return value is the pathname of the directory.

    Arguments are as for mkstemp, except that the 'text' argument is
    not accepted.

    The directory is readable, writable, and searchable only by the
    creating user.

    Caller is responsible for deleting the directory when done with it.
    """

    if dir is None:
        dir = gettempdir()

    names = _get_candidate_names()

    for seq in xrange(TMP_MAX):
        name = names.next()
        file = _os.path.join(dir, prefix + name + suffix)
        try:
            _os.mkdir(file, 0700)
            return file
        except OSError, e:
            if e.errno == _errno.EEXIST:
                continue # try again
            if (_os.name == 'nt' and e.errno == _errno.EACCES and
                _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
                # On windows, when a directory with the chosen name already
                # exists, EACCES error code is returned instead of EEXIST.
                continue
            raise 
Example #22
Source File: mailer.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_mime_attachments(self):
		"""
		Return a :py:class:`.MessageAttachments` object containing both the images and
		raw files to be included in sent messages.

		:return: A namedtuple of both files and images in their MIME containers.
		:rtype: :py:class:`.MessageAttachments`
		"""
		files = []
		# allow the attachment_file.post_processing to be attached instead of
		# attachment_file so attachment_file can be used as an input for
		# arbitrary operations to modify without over writing the original
		attachment_file = self.config.get('mailer.attachment_file.post_processing')
		delete_attachment_file = False
		if attachment_file is not None:
			if not isinstance(attachment_file, str):
				raise TypeError('config option mailer.attachment_file.post_processing is not a readable file')
			if not os.path.isfile(attachment_file) and os.access(attachment_file, os.R_OK):
				raise ValueError('config option mailer.attachment_file.post_processing is not a readable file')
			self.config['mailer.attachment_file.post_processing'] = None
			delete_attachment_file = True
		else:
			attachment_file = self.config.get('mailer.attachment_file')
		if attachment_file:
			attachfile = mime.base.MIMEBase(*mimetypes.guess_type(attachment_file))
			attachfile.set_payload(open(attachment_file, 'rb').read())
			encoders.encode_base64(attachfile)
			attachfile.add_header('Content-Disposition', "attachment; filename=\"{0}\"".format(os.path.basename(attachment_file)))
			files.append(attachfile)
			if delete_attachment_file and os.access(attachment_file, os.W_OK):
				os.remove(attachment_file)

		images = []
		for attachment_file, attachment_name in template_environment.attachment_images.items():
			attachfile = mime.image.MIMEImage(open(attachment_file, 'rb').read())
			attachfile.add_header('Content-ID', "<{0}>".format(attachment_name))
			attachfile.add_header('Content-Disposition', "inline; filename=\"{0}\"".format(attachment_name))
			images.append(attachfile)
		return MessageAttachments(tuple(files), tuple(images)) 
Example #23
Source File: types.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, value, param, ctx):
        rv = value
        if self.resolve_path:
            rv = os.path.realpath(rv)

        try:
            st = os.stat(rv)
        except OSError:
            if not self.exists:
                return rv
            self.fail('%s "%s" does not exist.' % (
                self.path_type,
                filename_to_ui(value)
            ), param, ctx)

        if not self.file_okay and stat.S_ISREG(st.st_mode):
            self.fail('%s "%s" is a file.' % (
                self.path_type,
                filename_to_ui(value)
            ), param, ctx)
        if not self.dir_okay and stat.S_ISDIR(st.st_mode):
            self.fail('%s "%s" is a directory.' % (
                self.path_type,
                filename_to_ui(value)
            ), param, ctx)
        if self.writable and not os.access(value, os.W_OK):
            self.fail('%s "%s" is not writable.' % (
                self.path_type,
                filename_to_ui(value)
            ), param, ctx)
        if self.readable and not os.access(value, os.R_OK):
            self.fail('%s "%s" is not readable.' % (
                self.path_type,
                filename_to_ui(value)
            ), param, ctx)

        return rv 
Example #24
Source File: filebased.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._fname = None
        if 'file_path' in kwargs:
            self.file_path = kwargs.pop('file_path')
        else:
            self.file_path = getattr(settings, 'EMAIL_FILE_PATH', None)
        # Make sure self.file_path is a string.
        if not isinstance(self.file_path, six.string_types):
            raise ImproperlyConfigured('Path for saving emails is invalid: %r' % self.file_path)
        self.file_path = os.path.abspath(self.file_path)
        # Make sure that self.file_path is an directory if it exists.
        if os.path.exists(self.file_path) and not os.path.isdir(self.file_path):
            raise ImproperlyConfigured(
                'Path for saving email messages exists, but is not a directory: %s' % self.file_path
            )
        # Try to create it, if it not exists.
        elif not os.path.exists(self.file_path):
            try:
                os.makedirs(self.file_path)
            except OSError as err:
                raise ImproperlyConfigured(
                    'Could not create directory for saving email messages: %s (%s)' % (self.file_path, err)
                )
        # Make sure that self.file_path is writable.
        if not os.access(self.file_path, os.W_OK):
            raise ImproperlyConfigured('Could not write to directory: %s' % self.file_path)
        # Finally, call super().
        # Since we're using the console-based backend as a base,
        # force the stream to be None, so we don't default to stdout
        kwargs['stream'] = None
        super(EmailBackend, self).__init__(*args, **kwargs) 
Example #25
Source File: store.py    From dionaea with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, path, config=None):
        logger.debug("%s ready!" % (self.__class__.__name__))
        ihandler.__init__(self, path)

        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        if self.download_dir is None:
            raise LoaderError("Setting download.dir not configured")
        else:
            if not os.path.isdir(self.download_dir):
                raise LoaderError("'%s' is not a directory", self.download_dir)
            if not os.access(self.download_dir, os.W_OK):
                raise LoaderError("Not allowed to create files in the '%s' directory", self.download_dir) 
Example #26
Source File: files.py    From fac with MIT License 5 votes vote down vote up
def is_factorio_write_path(path):
        config_dir = os.path.join(path, 'config')
        mods_dir = os.path.join(path, 'mods')
        if not (os.path.isdir(config_dir) and
                os.path.isdir(mods_dir)):
            return False

        if not (os.access(config_dir, os.W_OK) and
                os.access(mods_dir, os.W_OK)):
            return False
        return True 
Example #27
Source File: cache.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def io_manager(self):
        if not self.enabled:
            return

        cache_dir = os.path.expandvars(
            self.session.GetParameter("cache_dir", cached=False))

        cache_dir = os.path.join(config.GetHomeDir(self.session), cache_dir)

        # Force the IO manager to be recreated if the cache dir has
        # changed. This allows the session to change it's cache directory on the
        # fly (which is actually done when setting it from the command line).
        if cache_dir != self.cache_dir:
            self._io_manager = None
            self.cache_dir = cache_dir

        if self._io_manager is None and cache_dir:
            # Cache dir may be specified relative to the home directory.
            if os.access(cache_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK):
                self._io_manager = PicklingDirectoryIOManager(
                    "%s/sessions" % cache_dir, session=self.session,
                    mode="w")

                self.cache_dir = cache_dir
            else:
                self.session.logging.warn(
                    "Cache directory inaccessible. Disabling.")
                self.enabled = False

        return self._io_manager 
Example #28
Source File: address_space_fuse.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def main():
    global server

    usage = """
Userspace address_space_fuse: mount all process address spaces.

%prog [options] image_name mount_point
"""

    server = AddressSpaceFuse(version="%prog " + fuse.__version__,
                     usage=usage,
                     dash_s_do='setsingle')

    # Disable multithreading: if you want to use it, protect all method of
    # XmlFile class with locks, in order to prevent race conditions
    server.multithreaded = False

    server.parser.add_option("-p", "--profile", default="Win7SP1x64",
                             help="Profile to use [default: %default]")

    server.parse(values = server, errex=1)

    ## Try to fix up the mount point if it was given relative to the
    ## CWD
    if server.fuse_args.mountpoint and not os.access(os.path.join("/",server.fuse_args.mountpoint), os.W_OK):
        server.fuse_args.mountpoint = os.path.join(os.getcwd(), server.fuse_args.mountpoint)

    server.main() 
Example #29
Source File: generate_data.py    From rtc-video-quality with Apache License 2.0 5 votes vote down vote up
def writable_dir(directory):
  if not os.path.isdir(directory) or not os.access(directory, os.W_OK):
    raise argparse.ArgumentTypeError("'%s' is either not a directory or cannot be opened for writing.\n" % directory)
  return directory 
Example #30
Source File: generate_graphs.py    From rtc-video-quality with Apache License 2.0 5 votes vote down vote up
def writable_dir(directory):
  if not os.path.isdir(directory) or not os.access(directory, os.W_OK):
    raise argparse.ArgumentTypeError("'%s' is either not a directory or cannot be opened for writing.\n" % directory)
  return directory