os.

Here are the examples of the python api os. taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 51

Project: mythbox
Source File: test_logfile.py
View license
    def testModePreservation(self):
        """
        Check rotated files have same permissions as original.
        """
        f = open(self.path, "w").close()
        os.chmod(self.path, 0707)
        mode = os.stat(self.path)[stat.ST_MODE]
        log = logfile.LogFile(self.name, self.dir)
        log.write("abc")
        log.rotate()
        self.assertEquals(mode, os.stat(self.path)[stat.ST_MODE])

Example 52

Project: mythbox
Source File: test_logfile.py
View license
    def test_defaultPermissions(self):
        """
        Test the default permission of the log file: if the file exist, it
        should keep the permission.
        """
        f = file(self.path, "w")
        os.chmod(self.path, 0707)
        currentMode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
        f.close()
        log1 = logfile.LogFile(self.name, self.dir)
        self.assertEquals(stat.S_IMODE(os.stat(self.path)[stat.ST_MODE]),
                          currentMode)

Example 53

Project: glow
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 54

Project: kupfer-adds
Source File: utils.py
View license
def get_destfile_in_directory(directory, filename, extension=None):
	"""Find a good destination for a file named @filename in path @directory.

	Like get_destpath_in_directory, but returns an open file object, opened
	atomically to avoid race conditions.

	Return (fileobj, filepath)
	"""
	# retry if it fails
	for retry in xrange(3):
		destpath = get_destpath_in_directory(directory, filename, extension)
		try:
			fd = os.open(destpath, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)
		except OSError, exc:
			pretty.print_error(__name__, exc)
		else:
			return (os.fdopen(fd, "wb"), destpath)
	return (None, None)

Example 55

Project: linkchecker
Source File: test_file.py
View license
def unzip (filename, targetdir):
    """Unzip given zipfile into targetdir."""
    if isinstance(targetdir, unicode):
        targetdir = str(targetdir)
    zf = zipfile.ZipFile(filename)
    for name in zf.namelist():
        if name.endswith('/'):
            os.mkdir(os.path.join(targetdir, name), 0700)
        else:
            outfile = open(os.path.join(targetdir, name), 'wb')
            try:
                outfile.write(zf.read(name))
            finally:
                outfile.close()

Example 56

Project: rsync-time-machine
Source File: time-machine.py
View license
def flock_exclusive():
    ''' lock so only one snapshot of current config is running '''
    fd = os.open(cfg['lock_file'], os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0600)
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return False
    return fd

Example 57

Project: PythonScript
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()

Example 58

Project: gogreen
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        def do_touch():
            fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
            os.close(fd)
            os.utime(self, None)
        dry("touch %s" % (self), do_touch)

Example 59

Project: paver
Source File: path2.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 60

View license
def createAndRunScript(text, stdIn="", printing=True, arguments=[], env_updates={}):
    # Output the text to a /tmp/ file
    scriptPath = "/tmp/" + uuid.uuid4().__str__()
    FILE = os.open(scriptPath, os.O_WRONLY | os.O_CREAT, 0770)
    os.write(FILE, text)
    os.close(FILE)
    cmd = [scriptPath]
    cmd.extend(arguments)

    # Run it
    ret = launchSubProcess(cmd, stdIn="", printing=True, env_updates=env_updates)

    # Remove the temp file
    os.remove(scriptPath)

    return ret

Example 61

Project: dusty
Source File: upgrade_test.py
View license
    @patch('dusty.commands.upgrade._get_binary_location')
    def test_move_preserves_permissions(self, fake_get_binary_location):
        os.chmod(self.file1_path, 0764)
        os.chmod(self.file2_path, 0777)
        previous_st_mode = os.stat(self.file1_path).st_mode
        fake_get_binary_location.return_value = self.file1_path
        _move_temp_binary_to_path(self.file2_path)
        self.assertEqual(os.stat(self.file1_path).st_mode, previous_st_mode)

Example 62

Project: lever
Source File: util.py
View license
def read_file(path):
    path = pathobj.os_stringify(path).encode('utf-8')
    fd = os.open(path, os.O_RDONLY, 0777)
    try:
        data = ""
        frame = os.read(fd, frame_size)
        while frame != "":
            data += frame
            frame = os.read(fd, frame_size)
    finally:
        os.close(fd)
    return data.decode('utf-8')

Example 63

Project: neuroConstruct
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()

Example 64

View license
def open_log_file(activity):
    i = 1
    while True:
        path = env.get_logs_path('%s-%s.log' % (activity.get_bundle_id(), i))
        try:
            fd = os.open(path, os.O_EXCL | os.O_CREAT | os.O_WRONLY, 0644)
            f = os.fdopen(fd, 'w', 0)
            return (path, f)
        except OSError, e:
            if e.errno == EEXIST:
                i += 1
            elif e.errno == ENOSPC:
                # not the end of the world; let's try to keep going.
                return ('/dev/null', open('/dev/null', 'w'))
            else:
                raise e

Example 65

Project: mixminion
Source File: Crypto.py
View license
def pk_PEM_save(rsa, filename, password=None):
    """Save a PEM-encoded private key to a file.  If <password> is provided,
       encrypt the key using the password."""
    fd = os.open(filename, os.O_WRONLY|os.O_CREAT,0600)
    f = os.fdopen(fd, 'w')
    if password:
        rsa.PEM_write_key(f, 0, password)
    else:
        rsa.PEM_write_key(f, 0)
    f.close()

Example 66

Project: PokemonGo-DesktopMap
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()

Example 67

Project: cloudpebble
Source File: archive.py
View license
@task(acks_late=True)
def export_user_projects(user_id):
    user = User.objects.get(pk=user_id)
    projects = Project.objects.filter(owner=user)
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
        filename = temp.name
        with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as z:
            for project in projects:
                add_project_to_archive(z, project, prefix='cloudpebble-export/')

        # Generate a URL
        u = uuid.uuid4().hex
        outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u, 'cloudpebble-export')
        os.makedirs(os.path.dirname(outfile), 0755)
        shutil.copy(filename, outfile)
        os.chmod(outfile, 0644)

Example 68

Project: gyp
Source File: flock_tool.py
View license
  def ExecFlock(self, lockfile, *cmd_list):
    """Emulates the most basic behavior of Linux's flock(1)."""
    # Rely on exception handling to report errors.
    # Note that the stock python on SunOS has a bug
    # where fcntl.flock(fd, LOCK_EX) always fails
    # with EBADF, that's why we use this F_SETLK
    # hack instead.
    fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666)
    if sys.platform.startswith('aix'):
      # Python on AIX is compiled with LARGEFILE support, which changes the
      # struct size.
      op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
    else:
      op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
    fcntl.fcntl(fd, fcntl.F_SETLK, op)
    return subprocess.call(cmd_list)

Example 69

Project: ganeti
Source File: filelock.py
View license
  @classmethod
  def Open(cls, filename):
    """Creates and opens a file to be used as a file-based lock.

    @type filename: string
    @param filename: path to the file to be locked

    """
    # Using "os.open" is necessary to allow both opening existing file
    # read/write and creating if not existing. Vanilla "open" will truncate an
    # existing file -or- allow creating if not existing.
    return cls(os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT, 0664), "w+"),
               filename)

Example 70

Project: openwrt-mt7620
Source File: test_all.py
View license
def get_new_environment_path() :
    path=get_new_path("environment")
    import os
    try:
        os.makedirs(path,mode=0700)
    except os.error:
        test_support.rmtree(path)
        os.makedirs(path)
    return path

Example 71

Project: tipfy
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 72

Project: PipelineConstructionSet
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 73

Project: mixminion
Source File: Crypto.py
View license
def pk_PEM_save(rsa, filename, password=None):
    """Save a PEM-encoded private key to a file.  If <password> is provided,
       encrypt the key using the password."""
    fd = os.open(filename, os.O_WRONLY|os.O_CREAT,0600)
    f = os.fdopen(fd, 'w')
    if password:
        rsa.PEM_write_key(f, 0, password)
    else:
        rsa.PEM_write_key(f, 0)
    f.close()

Example 74

Project: nozama-cloudsearch
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        def do_touch():
            fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
            os.close(fd)
            os.utime(self, None)
        dry("touch %s" % (self), do_touch)

Example 75

Project: scriptine
Source File: _path.py
View license
    @dry_guard
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 76

Project: sphinx-contrib
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 77

Project: treadmill
Source File: fs_test.py
View license
    @mock.patch('os.path.exists', mock.Mock(return_value=True))
    @mock.patch('treadmill.syscall.unshare.unshare', mock.Mock(return_value=0))
    @mock.patch('os.makedirs', mock.Mock(return_value=0))
    def test_chroot_init_empty_existing(self):
        """Checks that chroot can be done over existing empty dir."""
        fs.chroot_init('/var/bla')
        os.makedirs.assert_called_with('/var/bla', mode=0777)
        treadmill.syscall.unshare.unshare.assert_called_with(_CLONE_NEWNS)

Example 78

Project: kupfer-adds
Source File: utils.py
View license
def get_destfile_in_directory(directory, filename, extension=None):
	"""Find a good destination for a file named @filename in path @directory.

	Like get_destpath_in_directory, but returns an open file object, opened
	atomically to avoid race conditions.

	Return (fileobj, filepath)
	"""
	# retry if it fails
	for retry in xrange(3):
		destpath = get_destpath_in_directory(directory, filename, extension)
		try:
			fd = os.open(destpath, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)
		except OSError, exc:
			pretty.print_error(__name__, exc)
		else:
			return (os.fdopen(fd, "wb"), destpath)
	return (None, None)

Example 79

Project: djangothis
Source File: path.py
View license
    def touch(self):
        """ Set the access/modified times of this file to the current time.
        Create the file if it does not exist.
        """
        fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
        os.close(fd)
        os.utime(self, None)

Example 80

Project: hellanzb
Source File: Util.py
View license
def touch(fileName):
    """ Set the access/modified times of this file to the current time. Create the file if
    it does not exist """
    fd = os.open(fileName, os.O_WRONLY | os.O_CREAT, 0666)
    os.close(fd)
    os.utime(fileName, None)

Example 81

Project: PythonScript
Source File: test_all.py
View license
def get_new_environment_path() :
    path=get_new_path("environment")
    import os
    try:
        os.makedirs(path,mode=0700)
    except os.error:
        test_support.rmtree(path)
        os.makedirs(path)
    return path

Example 82

Project: pth-toolkit
Source File: posixacl.py
View license
    def test_setntacl_smbd_invalidate_getntacl_smbd(self):
        acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
        simple_acl_from_posix = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)(A;;0x001200a9;;;S-1-5-21-2212615479-2695158682-2101375467-513)(A;;;;;WD)"
        os.chmod(self.tempf, 0750)
        setntacl(self.lp, self.tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467", use_ntvfs=False)

        # This should invalidate the ACL, as we include the posix ACL in the hash
        (backend_obj, dbname) = checkset_backend(self.lp, None, None)
        backend_obj.wrap_setxattr(dbname,
                                  self.tempf, "system.fake_access_acl", "")

        #the hash will break, and we return an ACL based only on the mode
        facl = getntacl(self.lp, self.tempf, direct_db_access=False)
        anysid = security.dom_sid(security.SID_NT_SELF)
        self.assertEquals(simple_acl_from_posix, facl.as_sddl(anysid))

Example 83

Project: teuthology
Source File: ansible.py
View license
    def _archive_failures(self):
        if self.ctx.archive:
            archive_path = "{0}/ansible_failures.yaml".format(self.ctx.archive)
            log.info("Archiving ansible failure log at: {0}".format(
                archive_path,
            ))
            shutil.move(
                self.failure_log.name,
                archive_path
            )
            os.chmod(archive_path, 0664)

Example 84

Project: oleviewdotnet
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = open(rc, 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()
        try:
            os.chmod(rc, 0600)
        except OSError:
            # should do something better here
            pass

Example 85

Project: bleachbit
Source File: FileUtilities.py
View license
def wipe_contents(path, truncate=True):
    """Wipe files contents

    http://en.wikipedia.org/wiki/Data_remanence
    2006 NIST Special Publication 800-88 (p. 7): "Studies have
    shown that most of today's media can be effectively cleared
    by one overwrite"
    """
    size = getsize(path)
    try:
        f = open(path, 'wb')
    except IOError, e:
        if e.errno == errno.EACCES:  # permission denied
            os.chmod(path, 0200)  # user write only
            f = open(path, 'wb')

Example 86

Project: st2
Source File: test_wiring.py
View license
    def setUp(self):
        super(WiringTest, self).setUp()

        # Create temporary directory used by the tests
        _, self.temp_dir_path = tempfile.mkstemp()
        os.chmod(self.temp_dir_path, 0666)   # nosec

Example 87

Project: chipsec
Source File: config.py
View license
    def _store_pypirc(self, username, password):
        """Creates a default .pypirc file."""
        rc = self._get_rc_file()
        f = open(rc, 'w')
        try:
            f.write(DEFAULT_PYPIRC % (username, password))
        finally:
            f.close()
        try:
            os.chmod(rc, 0600)
        except OSError:
            # should do something better here
            pass

Example 88

Project: virt-test
Source File: utils_disk.py
View license
    @error.context_aware
    def close(self):
        error.context("Creating unattended install CD image %s" % self.path)
        g_cmd = ('mkisofs -o %s -max-iso9660-filenames '
                 '-relaxed-filenames -D --input-charset iso8859-1 '
                 '%s' % (self.path, self.mount))
        utils.run(g_cmd, verbose=DEBUG)

        os.chmod(self.path, 0755)
        cleanup(self.mount)
        logging.debug("unattended install CD image %s successfully created",
                      self.path)

Example 89

Project: autogit
Source File: test_index.py
View license
    def test_override_mode(self):
        st = os.stat_result((stat.S_IFREG + 0644, 131078, 64769L,
                154, 1000, 1000, 12288,
                1323629595, 1324180496, 1324180496))
        entry = index_entry_from_stat(st, "22" * 20, 0,
                mode=stat.S_IFREG + 0755)
        self.assertEqual(entry, (
            1324180496,
            1324180496,
            64769L,
            131078,
            33261,
            1000,
            1000,
            12288,
            '2222222222222222222222222222222222222222',
            0))

Example 90

View license
    def save(self, file_path):
        """
        Persist a Session Token to a file in JSON format.

        :type path: str
        :param path: The fully qualified path to the file where the
            the Session Token data should be written.  Any previous
            data in the file will be overwritten.  To help protect
            the credentials contained in the file, the permissions
            of the file will be set to readable/writable by owner only.
        """
        fp = open(file_path, 'wb')
        json.dump(self.to_dict(), fp)
        fp.close()
        os.chmod(file_path, 0600)

Example 91

Project: catnip
Source File: sandbox.py
View license
  def _EnvironmentSwap(self):
    @contextlib.contextmanager
    def Swapper():
      self._log.info('setting umask/PATH')
      last_umask = os.umask(022)
      last_path = os.environ['PATH']

Example 92

Project: usblock
Source File: registrar.py
View license
    def load_config(self):
        '''Read the config file and get all listed
        devices.
        '''
        self._create_conf_dir()
        self._config = ConfigParser.ConfigParser()
        opened_files = self._config.read(self._path)
        if not len(opened_files):
            try:
                file_handle = open(self._path, "w+")
                file_handle.close()
                os.chmod(self._path, 0600)
            except IOError:
                raise Exception("Failed to open %s for writing." %
                                self._path)
        else:
            self._set_values()

Example 93

Project: dvol
Source File: dvol.py
View license
def copyTo(fromPath, toPath):
    """
    Copy the contents of fromPath to toPath, assuming a quiesced filesystem,
    and that toPath doesn't exist, in a way that doesn't fail to copy special
    files like FIFOs.
    """
    if toPath.exists():
        raise Exception(
            "Cannot copy %(fromPath)s to %(toPath)s because it exists" %
            dict(toPath=toPath.path, fromPath=fromPath.path))
    subprocess.check_call(["cp", "-a", fromPath.path, toPath.path])
    os.chmod(toPath.path, 0777) # TODO add tests

Example 94

Project: syndicate
Source File: experimentd.py
View license
def upgrade( wfile, upgrade_url ):

   global EXPERIMENT_PROC
   
   fd = open("/tmp/experimentd.py", "w")
   rc = subprocess.call(["curl", "-ks", upgrade_url], stdout=fd)
   fd.close()
   if rc != 0:
      return rc
   else:
      stop_experiment( wfile, EXPERIMENT_PROC )
      shutdown()
      os.chmod("/tmp/experimentd.py", 0755)

Example 95

Project: synapse-agent
Source File: bootstrap.py
View license
def make_x509_request(uuid, csrpath, keypath):
    rsa = generateRSAKey()
    pkey = makePKey(rsa)
    req = X509.Request()
    req.set_pubkey(pkey)
    name = X509.X509_Name()
    name.CN = uuid
    req.set_subject_name(name)
    req.sign(pkey, 'sha1')
    req.save(csrpath)
    rsa.save_key(keypath, cipher=None)
    os.chmod(keypath, 0640)

Example 96

Project: livecd-tools
Source File: kickstart.py
View license
    def write_wepkey(self, network):
        if not network.wepkey:
            return

        p = self.path("/etc/sysconfig/network-scripts/keys-" + network.device)
        f = file(p, "w+")
        os.chmod(p, 0600)

Example 97

Project: plinth
Source File: random_seek.py
View license
def seek_rand(keyfile, seedfile):
    try:
        with open(keyfile, 'r') as f:
            app_id = f.read()
        log.debug('Read private key from %s' % keyfile)
    except Exception, err:
        log.debug('Exception: %s' % err.message)
        app_id = plinth.Switch.new_key()
        umask = os.umask(0177)

Example 98

Project: pydoop
Source File: common_hdfs_tests.py
View license
    def chmod_w_string(self):
        path = self._make_random_dir()
        self.fs.chmod(path, 0500)
        # each user
        self.__set_and_check_perm(path, "u+w", 0700)
        self.__set_and_check_perm(path, "g+w", 0720)
        self.__set_and_check_perm(path, "o+w", 0722)
        # each permission mode
        self.__set_and_check_perm(path, "o+r", 0726)
        self.__set_and_check_perm(path, "o+x", 0727)
        # subtract operation, and multiple permission modes
        self.__set_and_check_perm(path, "o-rwx", 0720)
        # multiple users
        self.__set_and_check_perm(path, "ugo-rwx", 0000)
        # 'a' user
        self.__set_and_check_perm(path, "a+r", 0444)
        # blank user -- should respect the user's umask
        umask = os.umask(0007)

Example 99

Project: livecd-tools
Source File: kickstart.py
View license
    def write_hosts(self, hostname):
        localline = ""
        if hostname and hostname != "localhost.localdomain":
            localline += hostname + " "
            l = hostname.split(".")
            if len(l) > 1:
                localline += l[0] + " "
        localline += "localhost.localdomain localhost"

        path = self.path("/etc/hosts")
        f = file(path, "w+")
        os.chmod(path, 0644)

Example 100

Project: terminal-tools
Source File: runimage.py
View license
def install_pulldocker():
    url = 'https://www.terminal.com/pulldocker.tgz'
    try:
        subprocess.call(['wget', '--no-check-certificate', url])
        tfile = tarfile.open("pulldocker.tgz", 'r:gz')
        tfile.extractall('.')
        shutil.copy2('pulldocker','/usr/local/bin/pulldocker')
        os.chmod('/usr/local/bin/pulldocker',0755)