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


Python os.unlink方法代码示例

本文整理汇总了Python中os.unlink方法的典型用法代码示例。如果您正苦于以下问题:Python os.unlink方法的具体用法?Python os.unlink怎么用?Python os.unlink使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


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

示例1: get_num_triggering_samples

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def get_num_triggering_samples(signature, samples):
    """
        Get number of samples triggering ClamAV signature _signature_.
        :param signature: A dictionary with keys 'type' for the signature type
            and 'signature' for the signature string.
        :param samples: A list of sample paths to scan.
        :returns: The number of samples triggering this signature.
    """
    handle, temp_sig = tempfile.mkstemp(suffix = "." + signature["type"])
    try:
        with os.fdopen(handle, "w") as f:
            f.write(signature["signature"])
        proc_clamscan = subprocess.Popen(["clamscan", 
                                          "-d", temp_sig,
                                          "--no-summary", "--infected"] + samples, 
                                         stdout = subprocess.PIPE,
                                         stderr = subprocess.PIPE)
        stdout, stderr = proc_clamscan.communicate()
        if not stdout:
            return 0
        else:
            return len(stdout.strip().split("\n"))
    finally:
        os.unlink(temp_sig) 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:26,代码来源:core.py

示例2: test_full_tokenizer

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def test_full_tokenizer(self):
        vocab_tokens = [
            "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
            "##ing", ","
        ]
        with tempfile.NamedTemporaryFile(delete=False) as vocab_writer:
            vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))

            vocab_file = vocab_writer.name

        tokenizer = tokenization.FullTokenizer(vocab_file)
        os.unlink(vocab_file)

        tokens = tokenizer.tokenize(u"UNwant\u00E9d,running")
        self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])

        self.assertAllEqual(
            tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9]) 
开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:20,代码来源:tokenization_test.py

示例3: whitelist_add

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def whitelist_add():
    log.info("whitelist_add called")
    try:
        file_ = request.files["file"]
        handle, filename = tempfile.mkstemp()
        os.close(handle)
        file_.save(filename)
        data = request.get_json()
        if data and "functions" in data:
            functions = data["functions"]
        else:
            functions = None
        bass.whitelist_add(filename, functions)
        os.unlink(filename)
    except KeyError:
        log.exception("")
        return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)

    return jsonify(message = "OK") 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:21,代码来源:server.py

示例4: release

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def release(self):
        """Release the lock by deleting `self.lockfile`."""
        if not self._lock.is_set():
            return False

        try:
            fcntl.lockf(self._lockfile, fcntl.LOCK_UN)
        except IOError:  # pragma: no cover
            pass
        finally:
            self._lock.clear()
            self._lockfile = None
            try:
                os.unlink(self.lockfile)
            except (IOError, OSError):  # pragma: no cover
                pass

            return True 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:20,代码来源:util.py

示例5: _job_pid

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def _job_pid(name):
    """Get PID of job or `None` if job does not exist.

    Args:
        name (str): Name of job.

    Returns:
        int: PID of job process (or `None` if job doesn't exist).
    """
    pidfile = _pid_file(name)
    if not os.path.exists(pidfile):
        return

    with open(pidfile, 'rb') as fp:
        pid = int(fp.read())

        if _process_exists(pid):
            return pid

    try:
        os.unlink(pidfile)
    except Exception:  # pragma: no cover
        pass 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:25,代码来源:background.py

示例6: _delete_directory_contents

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def _delete_directory_contents(self, dirpath, filter_func):
        """Delete all files in a directory.

        :param dirpath: path to directory to clear
        :type dirpath: ``unicode`` or ``str``
        :param filter_func function to determine whether a file shall be
            deleted or not.
        :type filter_func ``callable``

        """
        if os.path.exists(dirpath):
            for filename in os.listdir(dirpath):
                if not filter_func(filename):
                    continue
                path = os.path.join(dirpath, filename)
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.unlink(path)
                self.logger.debug('deleted : %r', path) 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:22,代码来源:workflow.py

示例7: create_command_listener

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def create_command_listener (baddr, port):
    try:
        if port is None:
            try:
                if os.path.exists(baddr):
                    os.unlink(baddr)
            except OSError:
                print 'could not remove old unix socket ' + baddr
                return
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.bind(baddr)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((baddr, int(port)))
    except socket.error , msg:
        print 'Bind failed on command interface ' + baddr + ' port ' + str(port) + ' Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n'
        return 
开发者ID:sdn-ixp,项目名称:iSDX,代码行数:19,代码来源:tnode.py

示例8: BuildImage

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def BuildImage(self, baseimage=None):
    """Actually build the image."""
    sb = self.CreateSparseBundle()
    mounted_sparsebundle = self.MountSparseBundle(sb)
    self.GetBaseImage(baseimage)
    mounted_image = self.MountOSXInstallESD()
    self.InstallOSX(mounted_sparsebundle, mounted_image)
    self.GetBuildPackages()
    pkgs = os.path.join(self.cwd, BUILD, 'Packages/')
    pkgreport = self.InstallPackages(pkgs, mounted_sparsebundle)
    self.WriteImageInfo(mounted_sparsebundle, pkgreport)
    image_file = self.ConvertSparseBundle(mounted_sparsebundle, sb)
    self.CleanUp(sb, image_file)
    self.PrintReport(pkgreport)
    self.newimagepath = image_file
    print ('Created new image: %s' % os.path.join(BUILD,
                                                  os.path.basename(image_file)))
    if os.path.exists(os.path.join(self.cwd, 'lastimage')):
      os.unlink(os.path.join(self.cwd, 'lastimage'))
    f = open(os.path.join(self.cwd, 'lastimage'), 'w')
    f.write('/Users/Shared/can_haz_image/%s' % os.path.basename(image_file))
    f.close() 
开发者ID:google,项目名称:macops,代码行数:24,代码来源:can_haz_image.py

示例9: run

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def run(self):
            versions = get_versions(verbose=True)
            target_versionfile = versionfile_source
            print("UPDATING %s" % target_versionfile)
            os.unlink(target_versionfile)
            f = open(target_versionfile, "w")
            f.write(SHORT_VERSION_PY % versions)
            f.close()
            _build_exe.run(self)
            os.unlink(target_versionfile)
            f = open(versionfile_source, "w")
            f.write(LONG_VERSION_PY % {"DOLLAR": "$",
                                       "TAG_PREFIX": tag_prefix,
                                       "PARENTDIR_PREFIX": parentdir_prefix,
                                       "VERSIONFILE_SOURCE": versionfile_source,
                                       })
            f.close() 
开发者ID:matthew-brett,项目名称:delocate,代码行数:19,代码来源:versioneer.py

示例10: test_copy_recurse_overwrite

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def test_copy_recurse_overwrite():
    # Check that copy_recurse won't overwrite pre-existing libs
    with InTemporaryDirectory():
        # Get some fixed up libraries to play with
        os.makedirs('libcopy')
        test_lib, liba, libb, libc = _copy_fixpath(
            [TEST_LIB, LIBA, LIBB, LIBC], 'libcopy')
        # Filter system libs

        def filt_func(libname):
            return not libname.startswith('/usr/lib')
        os.makedirs('subtree')
        # libb depends on liba
        shutil.copy2(libb, 'subtree')
        # If liba is already present, barf
        shutil.copy2(liba, 'subtree')
        assert_raises(DelocationError, copy_recurse, 'subtree', filt_func)
        # Works if liba not present
        os.unlink(pjoin('subtree', 'liba.dylib'))
        copy_recurse('subtree', filt_func) 
开发者ID:matthew-brett,项目名称:delocate,代码行数:22,代码来源:test_delocating.py

示例11: test

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def test():
    class aeff(wuy.Window):
        size = (100, 100)

        def init(self):
            asyncio.get_event_loop().call_later(2, self.exit)

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # the following line is needed
    # because pytest seems to execute from a different path
    # then the executable one (think freezed)
    # ex: it works without it, in a real context
    # ex: it's needed when pytest execute the test
    # IRL : it's not needed to change the path
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    wuy.PATH = os.getcwd()  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    cf = "web/aeff.html"
    if os.path.isfile(cf):
        os.unlink(cf)
    aeff()
    assert os.path.isfile(cf), "a default file can't be created !!!"
    os.unlink(cf) 
开发者ID:manatlan,项目名称:wuy,代码行数:26,代码来源:test_createDefaultHtmlFile.py

示例12: rename

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
开发者ID:jojoin,项目名称:cutout,代码行数:19,代码来源:posixemulation.py

示例13: delete_request

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def delete_request(common_name, user="root"):
    # Validate CN
    if not re.match(const.RE_COMMON_NAME, common_name):
        raise ValueError("Invalid common name")

    path, buf, csr, submitted = get_request(common_name)
    os.unlink(path)

    logger.info("Rejected signing request %s by %s" % (
        common_name, user))

    # Publish event at CA channel
    push.publish("request-deleted", common_name)

    # Write empty certificate to long-polling URL
    requests.delete(
        config.LONG_POLL_PUBLISH % hashlib.sha256(buf).hexdigest(),
        headers={"User-Agent": "Certidude API"}) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:20,代码来源:authority.py

示例14: sign

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def sign(common_name, profile, skip_notify=False, skip_push=False, overwrite=False, signer="root"):
    """
    Sign certificate signing request by it's common name
    """

    req_path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")
    with open(req_path, "rb") as fh:
        csr_buf = fh.read()
        header, _, der_bytes = pem.unarmor(csr_buf)
        csr = CertificationRequest.load(der_bytes)


    # Sign with function below
    cert, buf = _sign(csr, csr_buf, profile, skip_notify, skip_push, overwrite, signer)

    os.unlink(req_path)
    return cert, buf 
开发者ID:laurivosandi,项目名称:certidude,代码行数:19,代码来源:authority.py

示例15: socket_cleanup

# 需要导入模块: import os [as 别名]
# 或者: from os import unlink [as 别名]
def socket_cleanup():
    try:
        os.unlink(SOCKPATH)
    except FileNotFoundError:
        pass
    try:
        os.unlink(SOCKPATH2)
    except FileNotFoundError:
        pass
    # Run test function
    yield
    try:
        os.unlink(SOCKPATH2)
    except FileNotFoundError:
        pass
    try:
        os.unlink(SOCKPATH)
    except FileNotFoundError:
        pass 
开发者ID:huge-success,项目名称:sanic,代码行数:21,代码来源:test_unix_socket.py


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