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 1

Project: cauliflowervest
Source File: util.py
View license
def SafeOpen(path, mode, open_=open):
  """Opens a file, guaranteeing that its directory exists, and makes it 0600.

  Args:
    path: str, path to the file to open, just like open().
    mode: str, open mode to perform, just like open().
    open_: callable, dependency injection for tests only.
  Returns:
    A handle to the open file, just like open().
  """
  try:
    os.makedirs(os.path.dirname(path), 0700)
    os.mknod(path, 0600 | stat.S_IFREG)
  except OSError:
    # File exists.
    pass

  return open_(path, mode)

Example 2

Project: pyrocore
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 3

Project: genomics
Source File: test_utils.py
View license
    def setUp(self):
        """Build directory with test data

        """
        self.example_dir = ExampleDirLinks()
        self.wd = self.example_dir.create_directory()
        self.example_dir.add_file("unreadable.txt")
        self.example_dir.add_file("group_unreadable.txt")
        self.example_dir.add_file("group_unwritable.txt")
        self.example_dir.add_file("program.exe")
        os.chmod(self.example_dir.path("spider.txt"),0664)
        os.chmod(self.example_dir.path("web"),0775)
        os.chmod(self.example_dir.path("unreadable.txt"),0044)
        os.chmod(self.example_dir.path("group_unreadable.txt"),0624)
        os.chmod(self.example_dir.path("group_unwritable.txt"),0644)
        os.chmod(self.example_dir.path("program.exe"),0755)
        self.example_dir.add_link("program","program.exe")

Example 4

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 5

Project: scalarizr
Source File: openstack.py
View license
    def __init__(self):
        platform.Platform.__init__(self)
        if not linux.os.windows_family:
            # Work over [Errno -3] Temporary failure in name resolution
            # http://bugs.centos.org/view.php?id=4814
            os.chmod('/etc/resolv.conf', 0755)
        self._nova_conn_pool = LocalPool(_create_nova_connection)
        self._swift_conn_pool = LocalPool(_create_swift_connection)
        self._cinder_conn_pool = LocalPool(_create_cinder_connection)

Example 6

Project: django-sane-testing
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 7

Project: PokemonGo-Bot-Desktop
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 8

Project: datafari
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 9

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 10

Project: node-ninja
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 11

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 12

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 13

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 14

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 15

Project: pybbs
Source File: Utmp.py
View license
    @staticmethod
    def Lock():
        #try:
            #SemLock.Lock(Config.UCACHE_SEMLOCK, timeout = 10);
            #return 0;
        #except BusyError:
            #return -1;
#        Log.debug("Utmp.Lock enter()")
        lockf = os.open(Config.BBS_ROOT + "UTMP", os.O_RDWR | os.O_CREAT, 0600)
        if (lockf < 0):
            Log.error("Fail to open lock file!")
            raise Exception("fail to lock!")
        Util.FLock(lockf, shared = False)
#        Log.debug("Utmp.Lock succ()")
        return lockf

Example 16

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 17

Project: flask-todo
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 18

Project: WAPT
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 19

Project: gmvault
Source File: credential_utils.py
View license
    @classmethod
    def store_passwd(cls, email, passwd):
        """
           Encrypt and store gmail password
        """
        passwd_file = '%s/%s.passwd' % (gmvault_utils.get_home_dir_path(), email)
    
        fdesc = os.open(passwd_file, os.O_CREAT|os.O_WRONLY, 0600)
        
        cipher       = blowfish.Blowfish(cls.get_secret_key(cls.SECRET_FILEPATH % (gmvault_utils.get_home_dir_path())))
        cipher.initCTR()
    
        encrypted = cipher.encryptCTR(passwd)
        the_bytes = os.write(fdesc, encrypted)
    
        os.close(fdesc)
        
        if the_bytes < len(encrypted):
            raise Exception("Error: Cannot write password in %s" % (passwd_file))

Example 20

Project: pangyp
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 21

Project: mrepo
Source File: rpmSourceUtils.py
View license
def saveHeader(hdr):
#    print hdr
#    print type(hdr)
    cfg = config.initUp2dateConfig()
    fileName = "%s/%s.%s.hdr" % (cfg["storageDir"],
                                 string.join( (hdr['name'],
                                               hdr['version'],
                                               hdr['release']),
                                              "-"),
                                 hdr['arch'])

#    print fileName
    fd = os.open(fileName, os.O_WRONLY|os.O_CREAT, 0600)

    os.write(fd, hdr.unload())
    os.close(fd)

    return 1

Example 22

Project: fsq
Source File: enqueue.py
View license
    def setUp(self):
        super(TestEnqueue, self).setUp()
        for f,payload in ((_test_c.FILE, _test_c.PAYLOAD),
                          (_test_c.NON_ASCII_FILE,
                           _test_c.NON_ASCII_PAYLOAD)):
            fd = os.open(f, os.O_WRONLY|os.O_CREAT, 00640)
            try:
                written = 0
                payload = payload.encode('utf8')
                while written < len(payload):
                    written += os.write(fd, payload[written:])
            finally:
                os.close(fd)
        os.mkfifo(_test_c.FIFO, 00640)

Example 23

Project: github-tools
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 24

Project: fsq
Source File: FSQTestCase.py
View license
    def setUp(self):
        _test_c.COUNT = 0
        try:
            shutil.rmtree(_test_c.TEST_DIR)
        except (OSError, IOError, ), e:
            if e.errno != errno.ENOENT:
                raise e
        os.mkdir(_test_c.TEST_DIR, 00750)
        os.mkdir(_test_c.ROOT1, 00750)
        os.mkdir(_test_c.ROOT2, 00750)
        _c.FSQ_ROOT = _test_c.ROOT1
        normalize()

Example 25

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 26

Project: notifier
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 27

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 28

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 29

Project: robothon
Source File: test__datasource.py
View license
    def test_CachedHTTPFile(self):
        localfile = valid_httpurl()
        # Create a locally cached temp file with an URL based
        # directory structure.  This is similar to what Repository.open
        # would do.
        scheme, netloc, upath, pms, qry, frg = urlparse(localfile)
        local_path = os.path.join(self.repos._destpath, netloc)
        os.mkdir(local_path, 0700)

Example 30

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 31

Project: pymo
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 32

Project: pybbs
Source File: BCache.py
View license
    @staticmethod
    def Lock():
        lockfd = os.open(Config.BBS_ROOT + "bcache.lock", os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0600)
        if (lockfd == None):
            Log.warn("fail to create bcache.lock")
            return None
        BCache.SetReadOnly(False)
        fcntl.flock(lockfd, fcntl.LOCK_EX)
        return lockfd

Example 33

Project: google-apputils
Source File: file_util_test.py
View license
  def testWriteGroup(self):
    self.mox.StubOutWithMock(os, 'open')
    self.mox.StubOutWithMock(os, 'write')
    self.mox.StubOutWithMock(os, 'close')
    self.mox.StubOutWithMock(os, 'chown')
    gid = 'new gid'
    os.open(self.file_path, os.O_WRONLY | os.O_TRUNC | os.O_CREAT,
            0666).AndReturn(self.fd)
    os.write(self.fd, self.sample_contents)
    os.close(self.fd)
    os.chown(self.file_path, -1, gid)
    self.mox.ReplayAll()
    file_util.Write(self.file_path, self.sample_contents, gid=gid)
    self.mox.VerifyAll()

Example 34

Project: gitology
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 35

Project: dusty
Source File: repos_test.py
View license
    def setUp(self):
        super(TestReposCLI, self).setUp()
        busybox_single_app_bundle_fixture(num_bundles=1)
        single_specs_fixture()

        self.temp_repos_dir = mkdtemp()
        self.fake_override_dir = mkdtemp()
        self.fake_from_dir = mkdtemp()

        os.chmod(self.temp_repos_dir, 0777)
        os.chmod(self.fake_override_dir, 0777)
        os.chmod(self.fake_from_dir, 0777)

        self.fake_override_repo_location = os.path.join(self.fake_override_dir, 'fake-repo')
        self._set_up_fake_local_repo(path=self.fake_override_repo_location)
        self.fake_from_repo_location = os.path.join(self.fake_from_dir, 'fake-repo')
        self._set_up_fake_local_repo(path=self.fake_from_repo_location)
        self.fake_source_repo_location = '/tmp/fake-repo'
        self._set_up_fake_local_repo(path=self.fake_source_repo_location)

Example 36

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 37

Project: datafari
Source File: test_dumbdbm.py
View license
    @unittest.skipUnless(hasattr(os, 'chmod'), 'os.chmod not available')
    @unittest.skipUnless(hasattr(os, 'umask'), 'os.umask not available')
    def test_dumbdbm_creation_mode(self):
        try:
            old_umask = os.umask(0002)
            f = dumbdbm.open(_fname, 'c', 0637)

Example 38

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 39

Project: genomics
Source File: test_utils.py
View license
    def tearDown(self):
        """Remove directory with test data

        """
        os.chmod(self.example_dir.path("unreadable.txt"),0644)
        os.chmod(self.example_dir.path("group_unreadable.txt"),0644)
        os.chmod(self.example_dir.path("group_unwritable.txt"),0644)
        os.chmod(self.example_dir.path("program.exe"),0644)
        self.example_dir.delete_directory()

Example 40

Project: datafari
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 41

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 42

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 43

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 44

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 45

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 46

Project: mythbox
Source File: test_logfile.py
View license
    def tearDown(self):
        """
        Restore back write rights on created paths: if tests modified the
        rights, that will allow the paths to be removed easily afterwards.
        """
        os.chmod(self.dir, 0777)
        if os.path.exists(self.path):
            os.chmod(self.path, 0777)

Example 47

Project: kupfer
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 48

Project: brackets-shell
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 49

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 50

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)