当前位置: 首页>>代码示例>>Python>>正文


Python oct函数代码示例

本文整理汇总了Python中oct函数的典型用法代码示例。如果您正苦于以下问题:Python oct函数的具体用法?Python oct怎么用?Python oct使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了oct函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_copy_real_file

    def test_copy_real_file(self):
        """Typical usage of deprecated copyRealFile()"""
        # Use this file as the file to be copied to the fake file system
        fake_file = self.copyRealFile(self.filepath)

        self.assertTrue(
            'class TestCopyOrAddRealFile(TestPyfakefsUnittestBase)'
            in self.real_string_contents,
            'Verify real file string contents')
        self.assertTrue(
            b'class TestCopyOrAddRealFile(TestPyfakefsUnittestBase)'
            in self.real_byte_contents,
            'Verify real file byte contents')

        # note that real_string_contents may differ to fake_file.contents
        # due to newline conversions in open()
        self.assertEqual(fake_file.byte_contents, self.real_byte_contents)

        self.assertEqual(oct(fake_file.st_mode), oct(self.real_stat.st_mode))
        self.assertEqual(fake_file.st_size, self.real_stat.st_size)
        self.assertAlmostEqual(fake_file.st_ctime,
                               self.real_stat.st_ctime, places=5)
        self.assertAlmostEqual(fake_file.st_atime,
                               self.real_stat.st_atime, places=5)
        self.assertLess(fake_file.st_atime, self.real_stat.st_atime + 10)
        self.assertAlmostEqual(fake_file.st_mtime,
                               self.real_stat.st_mtime, places=5)
        self.assertEqual(fake_file.st_uid, self.real_stat.st_uid)
        self.assertEqual(fake_file.st_gid, self.real_stat.st_gid)
开发者ID:mrbean-bremen,项目名称:pyfakefs,代码行数:29,代码来源:fake_filesystem_unittest_test.py

示例2: test_post

    def test_post(self):

        uploaded_path = os.path.join(self.F_SUBFOLDER.path, 'testimage.jpg')
        self.assertFalse(site.storage.exists(uploaded_path))

        url = '?'.join([self.url, urlencode({'folder': self.F_SUBFOLDER.path_relative_directory})])

        with open(self.STATIC_IMG_PATH, "rb") as f:
            file_size = os.path.getsize(f.name)
            response = self.client.post(url, data={'qqfile': 'testimage.jpg', 'file': f}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        # Check we get OK response
        self.assertTrue(response.status_code == 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data["filename"], "testimage.jpg")
        self.assertEqual(data["temp_filename"], None)

        # Check the file now exists
        self.testfile = FileObject(uploaded_path, site=site)
        self.assertTrue(site.storage.exists(uploaded_path))

        # Check the file has the correct size
        self.assertTrue(file_size == site.storage.size(uploaded_path))

        # Check permissions
        # TODO: break out into separate test
        if DEFAULT_PERMISSIONS is not None:
            permissions_default = oct(DEFAULT_PERMISSIONS)
            permissions_file = oct(os.stat(self.testfile.path_full).st_mode & 0o777)
            self.assertTrue(permissions_default == permissions_file)
开发者ID:TitanEntertainmentGroup,项目名称:django-filebrowser-no-grappelli,代码行数:30,代码来源:test_sites.py

示例3: gen_items

def gen_items (rootdir, verbose=False):
    global locked_dirs

    if os.path.isfile(rootdir):

        file_path = rootdir

        dir_path = os.path.dirname(rootdir)
        file_name = os.path.basename(rootdir)

        perm = oct(os.lstat(file_path).st_mode & 0o777).rjust(4, '0')[1:]

        action = get_file_action(perm, dir_path, file_name)

        if (action != 'ign' and action != perm) or verbose:
            yield (action, 'f', perm, dir_path + '/' + file_name)

        return

    for dir_path, sub_dirs, files in os.walk(rootdir):
        perm = oct(os.lstat(dir_path).st_mode & 0o777).rjust(4, '0')[1:]

        action = get_dir_action(perm, dir_path, sub_dirs, files)

        if action == 'ign' or action == 'non':
            if verbose:
                for i in ignore_tree(dir_path):
                    yield i
            del sub_dirs[:]
        else:
            if action != perm or (action == perm and verbose):
                yield (action, 'd', perm, dir_path)

            ign_sub_dir_list = get_ignore_sub_dirs_list(sub_dirs)

            if verbose:
                for i in ign_sub_dir_list:
                    for j in ignore_tree(dir_path + '/' + i):
                        yield j

            for i in ign_sub_dir_list:
                sub_dirs.remove(i)

            # may have problem to walk
            for i in sub_dirs:
                perm = oct(os.lstat(dir_path + '/' + i).st_mode & 0o777).rjust(4, '0')[1:]
                if re.match(r'^.*[0123].*$', perm):
                    locked_dirs.append(
                        '[{perm}] {itemname}'.format(
                        perm=perm,
                        itemname=dir_path+'/'+i) )

            for file_name in files:
                perm = oct(os.lstat(dir_path + '/' + file_name).st_mode & 0o777).rjust(4, '0')[1:]
                action = get_file_action(perm, dir_path, file_name)

                output = False

                if (action != 'ign' and action != perm) or verbose:
                    yield (action, 'f', perm, dir_path + '/' + file_name)
开发者ID:pi314,项目名称:rchmod,代码行数:60,代码来源:rchmod.py

示例4: SetMode

 def SetMode(self, mode):
     """Set the mode value of the display"""
     if self._mode == DEC_MODE:
         tmp = self.GetValAsInt()
         if mode == OCT_MODE:
             val = oct(tmp)
         elif mode == HEX_MODE:
             val = str(hex(tmp))
             val = '0x' + val.lstrip('0x').upper()
         else:
             val = self._val
     elif self._mode == OCT_MODE:
         tmp = self._val.lstrip('0').rstrip('L')
         if not len(tmp):
             tmp = '0'
         if mode == DEC_MODE and len(tmp):
             val = int(tmp, 8)
         elif mode == HEX_MODE and len(tmp):
             val = str(hex(int(tmp, 8)))
             val = '0x' + val.lstrip('0x').upper()
         else:
             val = self._val
     else:
         tmp = self._val.lstrip('0x').rstrip('L')
         if not len(tmp):
             tmp = '0'
         if mode == DEC_MODE:
             val = int(tmp, 16)
         elif mode == OCT_MODE:
             val = oct(int(tmp, 16))
         else:
             val = self._val
     self._val = str(val)
     self._mode = mode
     self.Refresh()
开发者ID:Sureiya,项目名称:Rafiki,代码行数:35,代码来源:calc.py

示例5: check_ftype

def check_ftype(objs):
    """ Checks the filetype, permissions and uid,gid of the
    pkgdg object(objs) sent to it. Returns two dicts: ed and pd
    (the error_dict with a descriptive explanantion of the problem
    if present, none otherwise, the perm_dict with a description of
    the incoorect perms if present, none otherwise
    """
    ed = None
    pd = None
    lst_var = os.lstat(objs["path"])
    ftype, perm = get_ftype_and_perm(lst_var.st_mode)
    if ftype != objs["kind"]:
        ed = dict([('path', objs["path"]),
                ('problem', 'Expected %s, Got %s' %(objs["kind"], ftype)),
                ('pkgdb_entry', objs)])
    pdtmp = ''
    if perm!=objs["mode"]:
        pdtmp+="\nExpected MODE: %s, Got: %s" %(oct(objs["mode"]), oct(perm))
    if lst_var.st_uid!=objs["uid"]:
        pdtmp+="\nExpected UID: %s, Got: %s" %(objs["uid"], lst_var.st_uid)
    if lst_var.st_gid!=objs["gid"]:
        pdtmp+="\nExpected GID: %s, Got: %s" %(objs["gid"], lst_var.st_gid)
    if pdtmp and not objs["path"].endswith(".pyc"):
        pd = dict([('path', objs["path"]),
                ('problem', pdtmp[1:]),
                ('pkgdb_entry', objs)])
    return ed, pd
开发者ID:georgekola,项目名称:freenas,代码行数:27,代码来源:Configuration.py

示例6: assert_file_permissions

 def assert_file_permissions(self, expected_permissions, name):
     full_path = self.full_path(name)
     actual_file_permissions = stat.S_IMODE(os.stat(full_path).st_mode)
     if sys.platform != "win32":
         self.assertEqual(oct(expected_permissions), oct(actual_file_permissions))
     else:
         self.assertEqual(oct(0o666), oct(actual_file_permissions))
开发者ID:esc,项目名称:pybuilder,代码行数:7,代码来源:integrationtest_support.py

示例7: test_something_typeConversions

    def test_something_typeConversions(self):
        import math

        self.assertEqual(complex(1), complex(Something(1)))
        self.assertEqual(oct(1), oct(Something(1)))
        self.assertEqual(hex(16), hex(Something(16)))
        self.assertEqual(math.trunc(math.pi), math.trunc(maybe(math.pi)))
开发者ID:amitsaha,项目名称:pymaybe,代码行数:7,代码来源:test_pymaybe.py

示例8: generate_specfile_pair

def generate_specfile_pair( data, output_fd=None ):
   """
   Generate a <Pair> section of the specfile.
   If output_fd is not None, write it to output_fd.
   Otherwise, return the string.
   """
   
   return_string = False 

   if output_fd is None:
      return_string = True
      output_fd = StringIO.StringIO()
   
   output_fd.write("  <Pair reval=\"%s\">\n" % data.reval_sec )
   
   if data.__class__.__name__ == "AG_file_data":
      # this is a file 
      output_fd.write("    <File perm=\"%s\">%s</File>\n" % (oct(data.perm), data.path))
      output_fd.write("    <Query type=\"%s\">%s</Query>\n" % (data.driver, data.query_string))
                              
   else:
      # this is a directory 
      output_fd.write("    <Dir perm=\"%s\">%s</Dir>\n" % (oct(data.perm), data.path))
      output_fd.write("    <Query type=\"%s\"></Query>\n" % (data.driver))
      
   output_fd.write("  </Pair>\n")
   
   if return_string:
      return output_fd.getvalue()
   else:
      return True 
开发者ID:iychoi,项目名称:syndicate-core,代码行数:31,代码来源:specfile.py

示例9: index

def index(directory,trim,excludedirs,excludefiles):
    stack = [directory]
    files = []
    while stack:
        directory = stack.pop()
        directory = os.path.abspath(directory)
        for file in os.listdir(directory):
            fullname = os.path.join(directory, file)
            truncname = fullname[trim:]
            if truncname not in excludedirs and truncname not in excludefiles:
                if os.path.isfile(fullname) and not os.path.islink(fullname):
                    mode = getStat(fullname)
                    files.append([truncname,fchksum.fmd5t(fullname)[0],oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isfile(fullname) and os.path.islink(fullname):
                    mode = getStat(fullname)
                    files.append([truncname,"symlink to file",oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isdir(fullname) and os.path.islink(fullname):
                    mode = getStat(fullname)
                    files.append([truncname,"symlink to directory",oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isdir(fullname) and not os.path.islink(fullname) and os.listdir(fullname) == []:
                    mode = getStat(fullname)
                    files.append([truncname,"empty dir",oct(mode[0]),str(mode[1]),str(mode[2])])
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    stack.append(fullname)
            else:
                print "excluding", fullname
    return files
开发者ID:twistor,项目名称:voluntus-update,代码行数:27,代码来源:updatelib.py

示例10: test_jobsub_setup

def test_jobsub_setup():
  # User 'test' triggers the setup of the examples.
  # 'hue' home will be deleted, the examples installed in the new one
  # and 'test' will try to access them.
  cluster = pseudo_hdfs4.shared_cluster()
  cluster.fs.setuser('test')

  username = 'hue'
  home_dir = '/user/%s/' % username
  finish = conf.REMOTE_DATA_DIR.set_for_testing('%s/jobsub' % home_dir)

  try:
    data_dir = conf.REMOTE_DATA_DIR.get()
    cluster.fs.setuser(cluster.fs.superuser)
    if cluster.fs.exists(home_dir):
      cluster.fs.rmtree(home_dir)
    cluster.fs.setuser('test')

    jobsub_setup.Command().handle()

    cluster.fs.setuser('test')
    stats = cluster.fs.stats(home_dir)
    assert_equal(stats['user'], username)
    assert_equal(oct(stats['mode']), '040755') #04 because is a dir

    stats = cluster.fs.stats(data_dir)
    assert_equal(stats['user'], username)
    assert_equal(oct(stats['mode']), '041777')

    stats = cluster.fs.listdir_stats(data_dir)
    assert_equal(len(stats), 2) # 2 files inside
  finally:
    finish()
开发者ID:gigfork,项目名称:hue,代码行数:33,代码来源:tests.py

示例11: chmod

 def chmod ( self, path, mode ):
     print '*** chmod', path, oct(mode)
     from DIRAC.DataManagementSystem.Client.FileCatalogClientCLI import FileCatalogClientCLI
     from COMDIRAC.Interfaces import DCatalog
     FileCatalogClientCLI( DCatalog().catalog ).do_chmod(str(oct(mode&0777))[1:]+" "+path)
     #return -errno.ENOSYS
     return 0
开发者ID:DIRACGrid,项目名称:FSDIRAC,代码行数:7,代码来源:DiracFS.py

示例12: createdir

    def createdir(self, path, mode=None):
        parts = path.split("/")
        tmpPath = ""
        for part in parts:
            tmpPath = os.path.join(tmpPath, part)
            if tmpPath == "":
                tmpPath = "/"

            try:
                if mode:
                    self._iop.mkdir(tmpPath, mode)
                else:
                    self._iop.mkdir(tmpPath)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
                else:
                    if tmpPath == path and mode is not None:
                        statinfo = self._iop.stat(path)
                        curMode = statinfo[stat.ST_MODE]
                        if curMode != mode:
                            raise OSError(errno.EPERM,
                                          ("Existing %s "
                                           "permissions %s are not as "
                                           "requested %s") % (path,
                                                              oct(curMode),
                                                              oct(mode)))
开发者ID:myOvirt,项目名称:vdsm,代码行数:27,代码来源:outOfProcess.py

示例13: test_do_upload

def test_do_upload(test):
    """
    Test the actual uploading
    """

    url = reverse('%s:fb_do_upload' % test.site_name)
    url = '?'.join([url, urlencode({'folder': test.tmpdir.path_relative_directory, 'qqfile': 'testimage.jpg'})])

    with open(os.path.join(FILEBROWSER_PATH, 'static/filebrowser/img/testimage.jpg'), "rb") as f:
        file_size = os.path.getsize(f.name)
        response = test.c.post(url, data={'qqfile': 'testimage.jpg', 'file': f}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    # Check we get OK response
    test.assertTrue(response.status_code == 200)

    # Check the file now exists
    path = os.path.join(test.tmpdir.path, 'testimage.jpg')
    test.testfile = FileObject(path, site=test.site)
    test.assertTrue(test.site.storage.exists(path))

    # Check the file has the correct size
    test.assertTrue(file_size == test.site.storage.size(path))

    # Check permissions
    if DEFAULT_PERMISSIONS is not None:
        permissions_default = oct(DEFAULT_PERMISSIONS)
        permissions_file = oct(os.stat(test.testfile.path_full).st_mode & 777)
        test.assertTrue(permissions_default == permissions_file)
开发者ID:pureblue,项目名称:django-filebrowser-no-grappelli,代码行数:28,代码来源:test_sites.py

示例14: posix_chmod_parser

	def posix_chmod_parser(self,test_path):
		log_path = "../logs/log_run.log"
		self.test_dir = test_path  # path to test dir with files and dirs (different chmod)
		print
		print "    [Get directories and files in test directory " + self.test_dir + "] :"
		self.log_add(log_path,"[Get directories and files in test directory " + self.test_dir + "] :")
		print
		for dir_n, dir_nn, file_nn in os.walk(self.test_dir):
			blank = 0
			for dir2 in dir_nn:			# Get directories
				dir_true = os.path.join(dir_n, dir2)
				mode_d = int(oct(os.stat(dir_true).st_mode)[-3:])  # get chmod (permissions) ___uga
				print "    Get dir: " + dir_true + " permissions: " + str(mode_d)
				self.log_add(log_path,"Get dir: " + dir_true + " permissions: " + str(mode_d))
				blank += 1
				self.dirs.append(dir_true)
				if mode_d in range (444,446):	#444 (r--r--r--) .. 446 (r--r--rw-)
					self.dir_r.append(dir_true)
				elif mode_d in range (666,778): #666 (rw-rw-rw-) .. 777 (rwxrwxrwx))
					self.dir_rw.append(dir_true)
			for file_n in file_nn:			# Get files
				file_true = os.path.join(dir_n, file_n)
				mode_f = int(oct(os.stat(file_true).st_mode)[-3:])			# get chmod (permissions) ___uga
				print "    Get file: " + file_true + " permissions: " + str(mode_f)
				self.log_add(log_path,"Get file: " + file_true + " permissions: " + str(mode_f))
				self.files.append(file_true) #444 = -r--r--r--  any can read  /  #666 = -rw-rw-rw-  any can read and write
				if mode_f in range(444, 446):  # 444 .. 446
					self.file_r.append(file_true)
				elif mode_f in range(666, 778):  # 666 .. 777
					self.file_rw.append(file_true)
		# add markers into the typles in order to find it in future tests
		self.files_chmod["r"] = self.file_r
		self.files_chmod["rw"] = self.file_rw
		self.dirs_chmod["r"] = self.dir_r
		self.dirs_chmod["rw"] = self.dir_rw
开发者ID:AleksNeStu,项目名称:NFSv4,代码行数:35,代码来源:generator_p.py

示例15: format

 def format(self, checktype, val):
     """ python 3: Octal literals are no longer of the form 0720; use 0o720 instead.
     """
     if sys.version_info > (3,0):
         return '0' + str(oct(val))[2:] if checktype=='mode' else str(val)
     else:
         return str(oct(val)) if checktype=='mode' else str(val)
开发者ID:lmiphay,项目名称:gentoo-oam,代码行数:7,代码来源:checkconfig.py


注:本文中的oct函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。