当前位置: 首页>>代码示例>>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;未经允许,请勿转载。