Python os.unlink() Examples

The following are 30 code examples of os.unlink(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: core.py    From BASS with GNU General Public License v2.0 9 votes vote down vote up
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) 
Example #2
Source File: server.py    From BASS with GNU General Public License v2.0 8 votes vote down vote up
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") 
Example #3
Source File: util.py    From wechat-alfred-workflow with MIT License 6 votes vote down vote up
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 
Example #4
Source File: can_haz_image.py    From macops with Apache License 2.0 6 votes vote down vote up
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() 
Example #5
Source File: tnode.py    From iSDX with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: authority.py    From certidude with MIT License 6 votes vote down vote up
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"}) 
Example #7
Source File: workflow.py    From wechat-alfred-workflow with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: authority.py    From certidude with MIT License 6 votes vote down vote up
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 
Example #9
Source File: testpatch.py    From jawfish with MIT License 6 votes vote down vote up
def test_patch_stopall(self):
        unlink = os.unlink
        chdir = os.chdir
        path = os.path
        patch('os.unlink', something).start()
        patch('os.chdir', something_else).start()

        @patch('os.path')
        def patched(mock_path):
            patch.stopall()
            self.assertIs(os.path, mock_path)
            self.assertIs(os.unlink, unlink)
            self.assertIs(os.chdir, chdir)

        patched()
        self.assertIs(os.path, path) 
Example #10
Source File: background.py    From wechat-alfred-workflow with MIT License 6 votes vote down vote up
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 
Example #11
Source File: tokenization_test.py    From BERT-Classification-Tutorial with Apache License 2.0 6 votes vote down vote up
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]) 
Example #12
Source File: versioneer.py    From delocate with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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() 
Example #13
Source File: test_unix_socket.py    From sanic with MIT License 6 votes vote down vote up
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 
Example #14
Source File: test_createDefaultHtmlFile.py    From wuy with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #15
Source File: file.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def _delete_measures_files_for_metric(self, metric_id, files):
        for f in files:
            try:
                os.unlink(self._build_measure_path(metric_id, f))
            except OSError as e:
                # Another process deleted it in the meantime, no prob'
                if e.errno != errno.ENOENT:
                    raise
        try:
            os.rmdir(self._build_measure_path(metric_id))
        except OSError as e:
            # ENOENT: ok, it has been removed at almost the same time
            #         by another process
            # ENOTEMPTY: ok, someone pushed measure in the meantime,
            #            we'll delete the measures and directory later
            # EEXIST: some systems use this instead of ENOTEMPTY
            if e.errno not in (errno.ENOENT, errno.ENOTEMPTY, errno.EEXIST):
                raise 
Example #16
Source File: test_delocating.py    From delocate with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #17
Source File: posixemulation.py    From cutout with MIT License 6 votes vote down vote up
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 
Example #18
Source File: test_unix_socket.py    From sanic with MIT License 5 votes vote down vote up
def test_socket_replaced_with_file():
    app = Sanic(name=__name__)

    @app.listener("after_server_start")
    async def hack(app, loop):
        os.unlink(SOCKPATH)
        with open(SOCKPATH, "w") as f:
            f.write("Not a socket")
        app.stop()

    app.run(host="myhost.invalid", unix=SOCKPATH) 
Example #19
Source File: KeyLoadStoreTests.py    From joeecc with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(self, *args):
		assert(self._filename is not None)
		os.unlink(self._filename) 
Example #20
Source File: test_io.py    From audio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _test_1_save(self, test_filepath, normalization):
        # load signal
        x, sr = torchaudio.load(test_filepath, normalization=normalization)

        # check save
        new_filepath = os.path.join(self.test_dirpath, "test.wav")
        torchaudio.save(new_filepath, x, sr)
        self.assertTrue(os.path.isfile(new_filepath))
        os.unlink(new_filepath)

        # check automatic normalization
        x /= 1 << 31
        torchaudio.save(new_filepath, x, sr)
        self.assertTrue(os.path.isfile(new_filepath))
        os.unlink(new_filepath)

        # test save 1d tensor
        x = x[0, :]  # get mono signal
        x.squeeze_()  # remove channel dim
        torchaudio.save(new_filepath, x, sr)
        self.assertTrue(os.path.isfile(new_filepath))
        os.unlink(new_filepath)

        # don't allow invalid sizes as inputs
        with self.assertRaises(ValueError):
            x.unsqueeze_(1)  # L x C not C x L
            torchaudio.save(new_filepath, x, sr)

        with self.assertRaises(ValueError):
            x.squeeze_()
            x.unsqueeze_(1)
            x.unsqueeze_(0)  # 1 x L x 1
            torchaudio.save(new_filepath, x, sr)

        # don't save to folders that don't exist
        with self.assertRaises(OSError):
            new_filepath = os.path.join(self.test_dirpath, "no-path",
                                        "test.wav")
            torchaudio.save(new_filepath, x, sr) 
Example #21
Source File: constants.py    From Adversarial_Video_Generation with MIT License 5 votes vote down vote up
def clear_dir(directory):
    """
    Removes all files in the given directory.

    @param directory: The path to the directory.
    """
    for f in os.listdir(directory):
        path = os.path.join(directory, f)
        try:
            if os.path.isfile(path):
                os.unlink(path)
            elif os.path.isdir(path):
                shutil.rmtree(path)
        except Exception as e:
            print(e) 
Example #22
Source File: test_unix_socket.py    From sanic with MIT License 5 votes vote down vote up
def test_socket_deleted_while_running():
    app = Sanic(name=__name__)

    @app.listener("after_server_start")
    async def hack(app, loop):
        os.unlink(SOCKPATH)
        app.stop()

    app.run(host="myhost.invalid", unix=SOCKPATH) 
Example #23
Source File: test_cli.py    From certidude with MIT License 5 votes vote down vote up
def clean_client():
    assert os.getuid() == 0 and os.getgid() == 0
    files = [
        "/etc/certidude/client.conf",
        "/etc/certidude/services.conf",
        "/etc/certidude/client.conf.d/ca.conf",
        "/etc/certidude/services.conf.d/ca.conf",
        "/etc/certidude/authority/ca.example.lan/ca_cert.pem",
        "/etc/certidude/authority/ca.example.lan/client_key.pem",
        "/etc/certidude/authority/ca.example.lan/server_key.pem",
        "/etc/certidude/authority/ca.example.lan/client_req.pem",
        "/etc/certidude/authority/ca.example.lan/server_req.pem",
        "/etc/certidude/authority/ca.example.lan/client_cert.pem",
        "/etc/certidude/authority/ca.example.lan/server_cert.pem",
        "/etc/NetworkManager/system-connections/IPSec to ipsec.example.lan",
        "/etc/NetworkManager/system-connections/OpenVPN to vpn.example.lan",
    ]
    for path in files:
        if os.path.exists(path):
            os.unlink(path)

    # Remove client storage area
    if os.path.exists("/tmp/ca.example.lan"):
        for filename in os.listdir("/tmp/ca.example.lan"):
            if filename.endswith(".pem"):
                os.unlink(os.path.join("/tmp/ca.example.lan", filename))

    # Reset IPsec stuff
    with open("/etc/ipsec.conf", "w") as fh: # TODO: make compatible with Fedora
        pass
    with open("/etc/ipsec.secrets", "w") as fh: # TODO: make compatible with Fedora
        pass 
Example #24
Source File: setup.py    From oscrypto with MIT License 5 votes vote down vote up
def run(self):
        sub_folders = ['build', 'temp', '%s.egg-info' % PACKAGE_NAME]
        if self.all:
            sub_folders.append('dist')
        for sub_folder in sub_folders:
            full_path = os.path.join(PACKAGE_ROOT, sub_folder)
            if os.path.exists(full_path):
                shutil.rmtree(full_path)
        for root, dirs, files in os.walk(os.path.join(PACKAGE_ROOT, PACKAGE_NAME)):
            for filename in files:
                if filename[-4:] == '.pyc':
                    os.unlink(os.path.join(root, filename))
            for dirname in list(dirs):
                if dirname == '__pycache__':
                    shutil.rmtree(os.path.join(root, dirname)) 
Example #25
Source File: versioneer.py    From btle-sniffer with MIT License 5 votes vote down vote up
def write_to_version_file(filename, versions):
    """Write the given version number to the given _version.py file."""
    os.unlink(filename)
    contents = json.dumps(versions, sort_keys=True,
                          indent=1, separators=(",", ": "))
    with open(filename, "w") as f:
        f.write(SHORT_VERSION_PY % contents)

    print("set %s to '%s'" % (filename, versions["version"])) 
Example #26
Source File: setup.py    From oscrypto with MIT License 5 votes vote down vote up
def run(self):
        sub_folders = ['build', 'temp', '%s.egg-info' % TEST_PACKAGE_NAME]
        if self.all:
            sub_folders.append('dist')
        for sub_folder in sub_folders:
            full_path = os.path.join(TESTS_ROOT, sub_folder)
            if os.path.exists(full_path):
                shutil.rmtree(full_path)
        for root, dirs, files in os.walk(TESTS_ROOT):
            for filename in files:
                if filename[-4:] == '.pyc':
                    os.unlink(os.path.join(root, filename))
            for dirname in list(dirs):
                if dirname == '__pycache__':
                    shutil.rmtree(os.path.join(root, dirname)) 
Example #27
Source File: pdos.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def unlink(p):
    return os.unlink(p) 
Example #28
Source File: versioneer.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_to_version_file(filename, versions):
    """Write the given version number to the given _version.py file."""
    os.unlink(filename)
    contents = json.dumps(versions, sort_keys=True,
                          indent=1, separators=(",", ": "))
    with open(filename, "w") as f:
        f.write(SHORT_VERSION_PY % contents)

    print("set %s to '%s'" % (filename, versions["version"])) 
Example #29
Source File: test_js.py    From wuy with GNU General Public License v2.0 5 votes vote down vote up
def clean():
    cf = os.path.join(os.getcwd())
    if os.path.isfile(cf):
        os.unlink(cf) 
Example #30
Source File: versioneer.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        versions = get_versions(verbose=True)
        _build.run(self)
        # now locate _version.py in the new build/ directory and replace it
        # with an updated value
        target_versionfile = os.path.join(self.build_lib, versionfile_build)
        print("UPDATING %s" % target_versionfile)
        os.unlink(target_versionfile)
        f = open(target_versionfile, "w")
        f.write(SHORT_VERSION_PY % versions)
        f.close()