當前位置: 首頁>>代碼示例>>Python>>正文


Python os.mknod方法代碼示例

本文整理匯總了Python中os.mknod方法的典型用法代碼示例。如果您正苦於以下問題:Python os.mknod方法的具體用法?Python os.mknod怎麽用?Python os.mknod使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在os的用法示例。


在下文中一共展示了os.mknod方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: set_log

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def set_log(level, filename='spider.log'):
    """
    return a log file object
    根據提示設置log打印
    """
    if not os.path.isdir(LOG_DIR):
    	os.mkdir(LOG_DIR)
    log_file = os.path.join(LOG_DIR, filename)
    if not os.path.isfile(log_file):
        os.mknod(log_file)
        os.chmod(log_file, 0777)
    log_level_total = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARN, 'error': logging.ERROR,
                       'critical': logging.CRITICAL}
    logger_f = logging.getLogger('spider')
    logger_f.setLevel(logging.DEBUG)
    fh = logging.FileHandler(log_file,'a')
    fh.setLevel(log_level_total.get(level, logging.DEBUG))
    formatter = logging.Formatter('%(asctime)s  %(filename)s  [line:%(lineno)d] %(levelname)s  %(message)s')
    fh.setFormatter(formatter)
    logger_f.addHandler(fh)
    keep_fds = [fh.stream.fileno()]
    return logger_f,keep_fds 
開發者ID:shancang,項目名稱:spider,代碼行數:24,代碼來源:common.py

示例2: create_project_dirs

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def create_project_dirs(self):
        self.status('Creating project directories... ')
        try:
            os.mkdir(os.path.join(BASE_DIR, 'data'))
        except FileExistsError:
            pass
        try:
            os.mkdir(os.path.join(BASE_DIR, 'templates'))
        except FileExistsError:
            pass
        try:
            os.mkdir(os.path.join(BASE_DIR, 'static'))
        except FileExistsError:
            pass
        # os.mknod requires superuser permissions on osx, so create a blank file instead
        try:
            open(os.path.join(BASE_DIR, 'static/.keep'), 'w').close()
        except FileExistsError:
            pass
        try:
            os.mkdir(os.path.join(BASE_DIR, 'tmp'))
        except FileExistsError:
            pass
        self.ok() 
開發者ID:TOMToolkit,項目名稱:tom_base,代碼行數:26,代碼來源:tom_setup.py

示例3: test_mknod

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def test_mknod(self):
        # Test using mknod() to create a FIFO (the only use specified
        # by POSIX).
        support.unlink(support.TESTFN)
        mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
        try:
            posix.mknod(support.TESTFN, mode, 0)
        except OSError as e:
            # Some old systems don't allow unprivileged users to use
            # mknod(), or only support creating device nodes.
            self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
        else:
            self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))

        # Keyword arguments are also supported
        support.unlink(support.TESTFN)
        try:
            posix.mknod(path=support.TESTFN, mode=mode, device=0,
                dir_fd=None)
        except OSError as e:
            self.assertIn(e.errno, (errno.EPERM, errno.EINVAL)) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:23,代碼來源:test_posix.py

示例4: test_mknod_dir_fd

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def test_mknod_dir_fd(self):
        # Test using mknodat() to create a FIFO (the only use specified
        # by POSIX).
        support.unlink(support.TESTFN)
        mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
        f = posix.open(posix.getcwd(), posix.O_RDONLY)
        try:
            posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
        except OSError as e:
            # Some old systems don't allow unprivileged users to use
            # mknod(), or only support creating device nodes.
            self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
        else:
            self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
        finally:
            posix.close(f) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:18,代碼來源:test_posix.py

示例5: test_get_artifact

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def test_get_artifact(self,
                                mock_hub: testing.MockHub,
                                tmp_path):
        '''
        test heist.salt_master.get_artifact
        when artifact does not already exist
        '''
        t_name = secrets.token_hex()
        ver = '2019.2.1'

        art_l = os.path.join(tmp_path, f'salt-{ver}')
        os.mknod(art_l)

        mock_hub.artifact.salt.fetch.return_value = art_l
        mock_hub.heist.salt_master.latest.return_value = False
        ret = await heist.artifact.salt_artifact.get_artifact(mock_hub, t_name,
                                                              'asyncssh', tmp_path,
                                                              'linux', ver)
        assert ret 
開發者ID:saltstack,項目名稱:heist,代碼行數:21,代碼來源:test_salt_artifact.py

示例6: test_check_extraction

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def test_check_extraction(self):
    """Tests the check_extraction method."""

    test_files = {
        'bin': ['bzcat', 'echo'],
        'sbin': ['visudo', 'tune2fs'],
        'home': ['echo']
    }

    for subfolder, files in test_files.items():
      os.makedirs(os.path.join(self.extraction_dir, subfolder))
      for file in files:
        os.mknod(os.path.join(self.extraction_dir, subfolder, file))

    self.task.json_path = os.path.join(self.extraction_dir, 'hashes.json')
    self.task.binary_extraction_dir = self.extraction_dir

    binary_cnt, hash_cnt = self.task.check_extraction()

    self.assertEqual(binary_cnt, 5)
    self.assertEqual(hash_cnt, 4)

    # Test if hashes.json file is not generated.
    self.task.json_path = os.path.join(self.extraction_dir, 'non_exist')
    self.assertRaises(TurbiniaException, self.task.check_extraction) 
開發者ID:google,項目名稱:turbinia,代碼行數:27,代碼來源:binary_extractor_test.py

示例7: rsync_tmp

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def rsync_tmp(self, host):
        """
        發布代碼到目標主機的/tmp目錄
        :return:
        """
        if not isinstance(host, dict):
            raise ValueError()

        ip = host.get('ip')
        port = host.get('port', 22)
        user = host.get('user', 'root')
        password = host.get('password')

        local_code_path = self.local_dir + self.repo_name  # 處理後的本地代碼路徑
        rsync_tmp_cmd = "sshpass -p {} rsync -ahqzt --delete -e 'ssh -p {}  -o StrictHostKeyChecking=no '  {} {}@{}:{}".format(
            password, port, local_code_path, user, ip, '/tmp/')
        # print('[CMD:] ', rsync_tmp_cmd)
        rsync_status, rsync_output = exec_shell(rsync_tmp_cmd)
        if rsync_status == 0:
            # 同步完成刪除/tmp/repo_name目錄
            print('[Success]: rsync host:{} to /tmp/{} sucess...'.format(ip, self.repo_name))
        else:
            os.mknod(self.uuid_file)
            print('[Error]: rsync host:{} falied '.format(ip)) 
開發者ID:opendevops-cn,項目名稱:codo-publish,代碼行數:26,代碼來源:upload_code.py

示例8: dump

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def dump (folder, data) :
    os.makedirs(folder, exist_ok = True)
    nframes = data['cells'].shape[0]
    np.savetxt(os.path.join(folder, 'type.raw'),    data['atom_types'], fmt = '%d')
    np.savetxt(os.path.join(folder, 'type_map.raw'),    data['atom_names'], fmt = '%s')
    np.savetxt(os.path.join(folder, 'box.raw'),     np.reshape(data['cells'],    [nframes,  9]))
    np.savetxt(os.path.join(folder, 'coord.raw'),   np.reshape(data['coords'],   [nframes, -1]))
    if 'energies' in data :
        np.savetxt(os.path.join(folder, 'energy.raw'),  np.reshape(data['energies'], [nframes,  1]))
    if 'forces' in data :
        np.savetxt(os.path.join(folder, 'force.raw'),   np.reshape(data['forces'],   [nframes, -1]))
    if 'virials' in data :
        np.savetxt(os.path.join(folder, 'virial.raw'), np.reshape(data['virials'], [nframes, 9]))
    try:
        os.remove(os.path.join(folder, "nopbc"))
    except OSError:
        pass
    if data.get("nopbc", False):
        os.mknod(os.path.join(folder, "nopbc")) 
開發者ID:deepmodeling,項目名稱:dpdata,代碼行數:21,代碼來源:raw.py

示例9: evaluation

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def evaluation(val_dataloader, net, epoch, use_gpu = True, save_dir ='/home/song/workspace/deeplab/tmp/log_test'):
    """
    評估函數 計算mIOU
    """
    ioues = AverageMeter()
    net.eval()
    for ii, sample_batched in enumerate(val_dataloader):
        """
        inputs -- (bs, 3, 512, 512)
        labels -- (bs, 1, 512, 512) 像素值為0-20 and 255
        outputs-- (bs, 21,512, 512) 像素值為任意
        """
        inputs, labels = sample_batched['image'], sample_batched['label']
        bs_test = inputs.shape[1]
        inputs = inputs.cuda() if use_gpu else inputs
        labels = labels.cuda() if use_gpu else labels

        outputs = net(inputs)

        predictions = torch.max(outputs, 1)[1]
        """
        outputs -- (bs, 21, 512, 512)
        val, index = torch.max(outputs, 1) 返回tuple 表示找每行的最大值
        index表示坐標 shape[1, 512, 512] 表示有512*512個位置,每個位置返回一個坐標,表示通道
        iou表示這batchsize的平均iou
        """
        iou = get_iou(predictions, labels)
        ioues.update(iou, inputs.shape[0])
        print('Test <==>Epoch: {:03} batch:{:03d}/{:03d} IOU:{:.2f} mIOU:{:.2f}'.format(epoch, ii+1, len(val_dataloader), ioues.val, ioues.avg))


    save_file = os.path.join(save_dir, 'log_test.txt')
    if not os.path.isdir(save_dir):
        os.makedirs(save_dir)
        
    if not os.path.isfile(save_file):
        os.mknod(save_file)
    with open(save_file, 'a') as f:
        f.write('Test  <==> Epoch: {:03}  Miou:{:.2f} \n'.format(epoch, ioues.avg)) 
開發者ID:songdejia,項目名稱:DeepLab_v3_plus,代碼行數:41,代碼來源:test.py

示例10: makedev

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def makedev(self, tarinfo, targetpath):
        """Make a character or block device called targetpath.
        """
        if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
            raise ExtractError("special devices not supported by system")

        mode = tarinfo.mode
        if tarinfo.isblk():
            mode |= stat.S_IFBLK
        else:
            mode |= stat.S_IFCHR

        os.mknod(targetpath, mode,
                 os.makedev(tarinfo.devmajor, tarinfo.devminor)) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:16,代碼來源:tarfile.py

示例11: create_tunnel

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def create_tunnel(self):
        node = '/dev/net/tun'
        if not os.path.exists(node):
            os.makedirs(os.path.dirname(node), exist_ok=True)
            os.mknod(node, mode=0o640 | stat.S_IFCHR, device = os.makedev(10, 200)) 
開發者ID:dlenski,項目名稱:vpn-slice,代碼行數:7,代碼來源:linux.py

示例12: alert_setack

# 需要導入模塊: import os [as 別名]
# 或者: from os import mknod [as 別名]
def alert_setack():
    try:
        os.mknod('/var/www/alert.ack')
    except OSError:
        pass 
開發者ID:WLANThermo,項目名稱:WLANThermo_v2,代碼行數:7,代碼來源:wlt_2_nextion.py


注:本文中的os.mknod方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。