Python os.remove() Examples

The following are code examples for showing how to use os.remove(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: factotum   Author: Denubis   File: update.py    GNU General Public License v3.0 8 votes vote down vote up
def copytree(src, dst, symlinks = False, ignore = None):
	if not os.path.exists(dst):
		os.makedirs(dst)
		shutil.copystat(src, dst)
	lst = os.listdir(src)
	if ignore:
		excl = ignore(src, lst)
		lst = [x for x in lst if x not in excl]
	for item in lst:
		s = os.path.join(src, item)
		d = os.path.join(dst, item)
		if symlinks and os.path.islink(s):
			if os.path.lexists(d):
				os.remove(d)
			os.symlink(os.readlink(s), d)
			try:
				st = os.lstat(s)
				mode = stat.S_IMODE(st.st_mode)
				os.lchmod(d, mode)
			except:
				pass # lchmod not available
		elif os.path.isdir(s):
			copytree(s, d, symlinks, ignore)
		else:
			shutil.copy2(s, d) 
Example 2
Project: NordVPN-NetworkManager-Gui   Author: vfosterm   File: nord_nm_gui.py    GNU General Public License v3.0 7 votes vote down vote up
def import_ovpn(self):
        """
        Renames and imports the ovpn to the Network Manager
        Cleans up the temporary files
        """
        try:
            self.statusbar.showMessage("Importing Connection...")
            self.repaint()
            self.connection_name = self.generate_connection_name()
            ovpn_file = self.connection_name + '.ovpn'
            path = os.path.join(self.config_path, ovpn_file) #changes name from default
            shutil.copy(self.ovpn_path, path)
            os.remove(self.ovpn_path)
            output = subprocess.run(['nmcli', 'connection', 'import', 'type', 'openvpn', 'file', path])
            output.check_returncode()
            os.remove(path)

        except subprocess.CalledProcessError:
            self.statusbar.showMessage("ERROR: Importing VPN configuration") 
Example 3
Project: Coulomb   Author: DynamoDS   File: stacktrace_extractor.py    MIT License 6 votes vote down vote up
def writeDataToFile():
            if (len(stackTraces) == 0): # If no stack traces, skip
                if os.path.exists(out_path):
                    os.remove(out_path)
                return

            print (json.dumps(
                {
                    "StackTraces" : stackTraces,
                    "Tags" : list(tags),
                    "UserID": userId,
                    "WorkspaceVersion": version,
                    "SessionDuration": sessionEndMicroTime - sessionStartMicroTime,
                    "Date": sessionDate
                }), file=fo)


        # Process each line of the session file 
Example 4
Project: ubittool   Author: carlosperate   File: cmds.py    MIT License 6 votes vote down vote up
def _open_temp_html(html_str):
    """Create a temporary html file, open it in a browser and delete it.

    :param html_str: String to write to the temporary file.
    """
    fd, path = tempfile.mkstemp(suffix=".html")
    try:
        with os.fdopen(fd, "w") as tmp:
            # do stuff with temp file
            tmp.write(html_str)
        webbrowser.open("file://{}".format(os.path.realpath(path)))
    finally:
        # It can take a bit of time for the browser to open the file,
        # so wait some time before deleting it
        t = Timer(30.0, lambda del_f: os.remove(del_f), args=[path])
        t.start() 
Example 5
Project: ubittool   Author: carlosperate   File: test_cmds.py    MIT License 6 votes vote down vote up
def test_open_temp_html(mock_browser_open, mock_timer):
    """Check browser is requested with a file containing the given text."""
    html_content = "hello world"

    cmds._open_temp_html(html_content)

    # Get the URL sent to the browser and check the content
    assert mock_browser_open.call_count == 1
    url = mock_browser_open.call_args[0][0]
    assert url.startswith("file://")
    file_path = url[7:]
    with open(file_path, "r") as tmp_file:
        read_content = tmp_file.read()
    assert read_content == html_content

    # Timer was mocked, so remove file manually
    os.remove(file_path) 
Example 6
Project: malcode   Author: moonsea   File: copyasm.py    GNU General Public License v3.0 6 votes vote down vote up
def CopyFile(srcDir, desDir, filename):
    if not os.path.exists(desDir):
        try:
            os.makedirs(desDir)
        except:
            print '[-] Mkdir error'

    desfile = os.path.join(desDir, filename)
    if os.path.isfile(desfile):
        log('Ignore', filename, '[-]', subpath='copyasm')
        print '[-]Ignore ', filename
        return
        # os.remove(desfile)

    log('Copying', filename, subpath='copyasm')
    print '[+]Copying ', filename

    try:
        shutil.copy(srcDir, desDir)
    except:
        log('Copying error', filename, '[-]', subpath='copyasm')
        print '[-]Copy error ', filename 
Example 7
Project: alfred-yubikey-otp   Author: robertoriv   File: util.py    MIT License 6 votes vote down vote up
def atomic_writer(fpath, mode):
    """Atomic file writer.

    .. versionadded:: 1.12

    Context manager that ensures the file is only written if the write
    succeeds. The data is first written to a temporary file.

    :param fpath: path of file to write to.
    :type fpath: ``unicode``
    :param mode: sames as for :func:`open`
    :type mode: string

    """
    suffix = '.{}.tmp'.format(os.getpid())
    temppath = fpath + suffix
    with open(temppath, mode) as fp:
        try:
            yield fp
            os.rename(temppath, fpath)
        finally:
            try:
                os.remove(temppath)
            except (OSError, IOError):
                pass 
Example 8
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_backup(filename):
    import os, os.path
    backup = filename + '~'
    if os.path.lexists(backup):
        try:
            os.remove(backup)
        except os.error:
            print("Can't remove backup %r" % (backup,), file=sys.stderr)
        # end try
    # end if
    try:
        os.rename(filename, backup)
    except os.error:
        print("Can't rename %r to %r" % (filename, backup), file=sys.stderr)
    # end try
# end def make_backup 
Example 9
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def doRollover(self):
        """
        Do a rollover, as described in __init__().
        """
        if self.stream:
            self.stream.close()
            self.stream = None
        if self.backupCount > 0:
            for i in range(self.backupCount - 1, 0, -1):
                sfn = "%s.%d" % (self.baseFilename, i)
                dfn = "%s.%d" % (self.baseFilename, i + 1)
                if os.path.exists(sfn):
                    #print "%s -> %s" % (sfn, dfn)
                    if os.path.exists(dfn):
                        os.remove(dfn)
                    os.rename(sfn, dfn)
            dfn = self.baseFilename + ".1"
            if os.path.exists(dfn):
                os.remove(dfn)
            # Issue 18940: A file may not have been created if delay is True.
            if os.path.exists(self.baseFilename):
                os.rename(self.baseFilename, dfn)
        if not self.delay:
            self.stream = self._open() 
Example 10
Project: pyblish-win   Author: pyblish   File: dir_util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def remove_tree(directory, verbose=1, dry_run=0):
    """Recursively remove an entire directory tree.

    Any errors are ignored (apart from being reported to stdout if 'verbose'
    is true).
    """
    global _path_created

    if verbose >= 1:
        log.info("removing '%s' (and everything under it)", directory)
    if dry_run:
        return
    cmdtuples = []
    _build_cmdtuple(directory, cmdtuples)
    for cmd in cmdtuples:
        try:
            cmd[0](cmd[1])
            # remove dir from cache if it's already there
            abspath = os.path.abspath(cmd[1])
            if abspath in _path_created:
                del _path_created[abspath]
        except (IOError, OSError), exc:
            log.warn("error removing %s: %s", directory, exc) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_unicode_metadata_tgz(self):
        """
        Unicode name or version should not break building to tar.gz format.
        Reference issue #11638.
        """

        # create the sdist command with unicode parameters
        dist, cmd = self.get_cmd({'name': u'fake', 'version': u'1.0'})

        # create the sdist as gztar and run the command
        cmd.formats = ['gztar']
        cmd.ensure_finalized()
        cmd.run()

        # The command should have created the .tar.gz file
        dist_folder = join(self.tmp_dir, 'dist')
        result = os.listdir(dist_folder)
        self.assertEqual(result, ['fake-1.0.tar.gz'])

        os.remove(join(dist_folder, 'fake-1.0.tar.gz')) 
Example 12
Project: pyblish-win   Author: pyblish   File: config.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _clean(self, *filenames):
        if not filenames:
            filenames = self.temp_files
            self.temp_files = []
        log.info("removing: %s", ' '.join(filenames))
        for filename in filenames:
            try:
                os.remove(filename)
            except OSError:
                pass


    # XXX these ignore the dry-run flag: what to do, what to do? even if
    # you want a dry-run build, you still need some sort of configuration
    # info.  My inclination is to make it up to the real config command to
    # consult 'dry_run', and assume a default (minimal) configuration if
    # true.  The problem with trying to do it here is that you'd have to
    # return either true or false from all the 'try' methods, neither of
    # which is correct.

    # XXX need access to the header search path and maybe default macros. 
Example 13
Project: pyblish-win   Author: pyblish   File: test_basics.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test09_EnvRemoveAndRename(self):
        if not self.env:
            return

        if verbose:
            print '\n', '-=' * 30
            print "Running %s.test09_EnvRemoveAndRename..." % self.__class__.__name__

        # can't rename or remove an open DB
        self.d.close()

        newname = self.filename + '.renamed'
        self.env.dbrename(self.filename, None, newname)
        self.env.dbremove(newname)

    #---------------------------------------- 
Example 14
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_flags(self, flags):
        """Set the given flags and unset all others."""
        flags = set(flags)
        status_flags, xstatus_flags = '', ''
        for flag in ('R', 'O'):
            if flag in flags:
                status_flags += flag
                flags.remove(flag)
        for flag in ('D', 'F', 'A'):
            if flag in flags:
                xstatus_flags += flag
                flags.remove(flag)
        xstatus_flags += ''.join(sorted(flags))
        try:
            self.replace_header('Status', status_flags)
        except KeyError:
            self.add_header('Status', status_flags)
        try:
            self.replace_header('X-Status', xstatus_flags)
        except KeyError:
            self.add_header('X-Status', xstatus_flags) 
Example 15
Project: BERT-Classification-Tutorial   Author: Socialbird-AILab   File: download_glue.py    Apache License 2.0 5 votes vote down vote up
def download_and_extract(task, data_dir):
    print("Downloading and extracting %s..." % task)
    data_file = "%s.zip" % task
    urllib.request.urlretrieve(TASK2PATH[task], data_file)
    with zipfile.ZipFile(data_file) as zip_ref:
        zip_ref.extractall(data_dir)
    os.remove(data_file)
    print("\tCompleted!") 
Example 16
Project: NordVPN-NetworkManager-Gui   Author: vfosterm   File: nord_nm_gui.py    GNU General Public License v3.0 5 votes vote down vote up
def remove_connection(self):
        """
        Remove connection from network manager
        """
        try:
            connection = subprocess.run(['nmcli', 'connection', 'delete', self.connection_name])
            connection.check_returncode()
        except subprocess.CalledProcessError:
            self.statusbar.showMessage("ERROR: Failed to remove Connection", 2000) 
Example 17
Project: factotum   Author: Denubis   File: factotum.py    GNU General Public License v3.0 5 votes vote down vote up
def runFactorio(stdin=True):

	FACTORIOPATH = getFactorioPath()

	if not stdin:
		print("Interactive mode enabled. Server can only be quit with ctrl-C. /quit will only restart the server.")	
	phrase = generatePhrase(6)
	with open("/tmp/factorioRcon", "w") as phraseFile:
		phraseFile.write(phrase)

	with codecs.open("%s/config/settings.json" % (FACTORIOPATH), 'r+', encoding='utf-8') as settings_file:
		try:
			settingsJson = json.load(settings_file)
		except Exception as e:
			print("Problem with settings file.")
			print(e)
			sys.exit(1)


	if not filter(os.path.isfile, glob.glob('%s/saves/*.zip' % (FACTORIOPATH))):
		print("Cannot find a save file. Exiting.")
		sys.exit(1)

	nohup="nohup "

	if not stdin:
		print(nohup)
		nohup=""
	myprogram = {"cmd": "%s%s/bin/x64/factorio --rcon-port 27015 --rcon-password \"%s\" --start-server-load-latest --server-settings %s/config/settings.json" % (nohup, FACTORIOPATH, phrase, FACTORIOPATH) , "numprocesses": 1, "stop_timeout": 20, "close_child_stdin":stdin}

	arbiter = circus.get_arbiter([myprogram])
	try:
					
		arbiter.start()
	finally:
		os.remove("/tmp/factorioRcon")
		arbiter.stop()
		print(subprocess.check_output(['tail', '-13', '%s/factorio-current.log'%FACTORIOPATH]).decode("unicode_escape")) 
Example 18
Project: fs_image   Author: facebookincubator   File: filesystem_storage.py    MIT License 5 votes vote down vote up
def remove(self, sid: str) -> None:
        sid_path = self._path_for_storage_id(self.strip_key(sid))
        assert sid_path.startswith(self.base_dir + b'/')
        os.remove(sid_path)
        # Remove any empty directories up to `self.filesystem_path`.
        dir_path = sid_path.dirname()
        while dir_path != self.base_dir:
            try:
                os.rmdir(dir_path)
            except OSError:  # pragma: no cover
                break
            dir_path = dir_path.dirname() 
Example 19
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def remove_file(filepath):
    try:
        os.remove(filepath)
    except OSError as err:
        api.current_logger().error('Could not remove {0}: {1}.'.format(filepath, err)) 
Example 20
Project: mutatest   Author: EvanKepner   File: cache.py    MIT License 5 votes vote down vote up
def remove_existing_cache_files(src_loc: Path) -> None:
    """Remove cache files by name or by directory.

    In the directory instance, all cache files are removed but the directory is not.

    Args:
        src_loc: the file or directory that is a target for removal

    Returns:
        None, deletes cache files from disk.
    """

    def remove_cfile(srcfile: Path) -> None:
        """Remove the cache-file.

        Args:
            srcfile: the source file to determine the cache file

        Returns:
            None
        """
        cfile = get_cache_file_loc(srcfile.resolve())
        if cfile.exists():
            LOGGER.debug("Removing cache file: %s", cfile)
            os.remove(str(cfile))

    if src_loc.is_dir():
        for srcfile in Path(src_loc).rglob("*.py"):
            remove_cfile(srcfile)

    elif src_loc.suffix == ".py":
        remove_cfile(src_loc) 
Example 21
Project: Coulomb   Author: DynamoDS   File: feature_usage_jsons_shuffler.py    MIT License 5 votes vote down vote up
def flush():
    # Create one file per feature version
    for k in feature_versions_map.keys():
        out_full_path = out_path + "." + k + '.jsons'
        
        # Ensure we created all of the data files
        if out_full_path not in known_files:
            known_files.add(out_full_path)
            if os.path.exists(out_full_path):
                print ("Removing existing file: " + out_full_path)
                os.remove(out_full_path)
        
        sessions = feature_versions_map[k]
        feature_version = k

        with open(out_full_path, 'a') as f:
            for session_id in sessions.keys():
                data_to_dump = {
                    'feature_version' : feature_version,
                    'session_id' : session_id,
                    'features' : sessions[session_id]
                }

                if pretty_print_json_output:
                    f.write(json.dumps(data_to_dump, sort_keys=True, indent=2) + "\n")
                else:
                    f.write(json.dumps(data_to_dump) + "\n")
            f.flush()
    feature_versions_map.clear()


# Main function 
Example 22
Project: Coulomb   Author: DynamoDS   File: sorted_sessions_to_features.py    MIT License 5 votes vote down vote up
def extract_features(blob_name, features_blob_name, temp_path):
    log("Extract features for ({}): {} => {}".format(VERSION, blob_name, features_blob_name))

    blob_session_name = blob_name.split('/')[-1]
    features_session_name = features_blob_name.split('/')[-1]

    blob_path_to_proc = os.path.join(temp_path, blob_session_name)
    out_path = os.path.join(temp_path, features_session_name)
    
    log ("Downloading {} => {}".format(blob_name, blob_path_to_proc))
    download_blob(SESSIONS_BUCKET, blob_name, blob_path_to_proc)

    extract(blob_path_to_proc, out_path)
    log("Features extracted: {} => {}".format(blob_path_to_proc, out_path))

    if not os.path.exists(out_path):
        return False
        
    upload_blob(FEATURES_BUCKET, out_path, features_blob_name)

    log("About to remove: {}".format(blob_path_to_proc))
    os.remove(blob_path_to_proc)
    
    log("About to remove: {}".format(out_path))
    os.remove(out_path)

    return True 
Example 23
Project: ubittool   Author: carlosperate   File: make.py    MIT License 5 votes vote down vote up
def _rm_dir(dir_to_remove):
    """:param dir_to_remove: Directory to remove."""
    if os.path.isdir(dir_to_remove):
        print("Removing directory: {}".format(dir_to_remove))
        shutil.rmtree(dir_to_remove)
    else:
        print("Directory {} was not found.".format(dir_to_remove)) 
Example 24
Project: ubittool   Author: carlosperate   File: make.py    MIT License 5 votes vote down vote up
def _rm_file(file_to_remove):
    """:param file_to_remove: File to remove."""
    if os.path.isfile(file_to_remove):
        print("Removing file: {}".format(file_to_remove))
        os.remove(file_to_remove)
    else:
        print("File {} was not found.".format(file_to_remove)) 
Example 25
Project: ubittool   Author: carlosperate   File: make.py    MIT License 5 votes vote down vote up
def _rm_file_extension(scan_path, file_extension):
    """Remove all files with an specific extension from a given directory.

    :param scan_path: Directory to scan for file removal.
    :param file_extension: File extension of the files to remove
    """
    for root, dirs, files in os.walk(scan_path, topdown=False):
        for file_ in files:
            if file_.endswith(".{}".format(file_extension)):
                file_path = os.path.join(root, file_)
                _rm_file(file_path) 
Example 26
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def removeLink(self, link):
        if link in self.links:
            self.links.remove(link)
        if self in link.lists:
            link.lists.remove(self) 
Example 27
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def getLinks(self, nDaysOfRecentEdits=1):
        earliestRecentEdit = time.time() - nDaysOfRecentEdits * 24 * 3600

        recent = [x for x in self.links if x.lastEdit()[0] > earliestRecentEdit]
        popular = self.getPopularLinks()

        for L in recent:
            popular.remove(L)

        return recent, popular 
Example 28
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def save(self):
        #TODO: Make this get saved to a database, this is a temporary solution to prevent corruption
        tmpfile = cfg_fnDatabase + '.tmp'
        pickle.dump(self, open(tmpfile, "wb"))
        shutil.copyfile(tmpfile, cfg_fnDatabase)
        os.remove(tmpfile) 
Example 29
Project: mlbv   Author: kmac   File: session.py    GNU General Public License v3.0 5 votes vote down vote up
def destroy(self):
        if os.path.exists(COOKIE_FILE):
            os.remove(COOKIE_FILE)
        if os.path.exists(SESSION_FILE):
            os.remove(SESSION_FILE) 
Example 30
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    MIT License 5 votes vote down vote up
def rm_rf(*paths):
    from shutil import rmtree
    for path in paths:
        if os.path.isfile(path):
            print('removing file: ' + path)
            os.remove(path)
        elif os.path.isdir(path):
            print('removing directory and its contents: ' + path)
            rmtree(path) 
Example 31
Project: malcode   Author: moonsea   File: wingenasm.py    GNU General Public License v3.0 5 votes vote down vote up
def cleanFile(filename, filepath):
    filetype = filename.split('.')[-1]
    if (filetype == 'asm' or filetype == 'idb'):
        os.remove(filepath)
        print '[-] Clean ', filename
        return True

    # unpack file
    if (filetype == 'dump'):
        return False
    return True

    # return False 
Example 32
Project: malcode   Author: moonsea   File: getOpCode.py    GNU General Public License v3.0 5 votes vote down vote up
def checkFile(filepath):
    if os.path.exists(filepath):
        try:
            os.remove(filepath)
        except:
            print '[-] Delete error' 
Example 33
Project: malcode   Author: moonsea   File: winfailgenasm.py    GNU General Public License v3.0 5 votes vote down vote up
def cleanFile(filename, filepath):
    filetype = filename.split('.')[-1]
    if (filetype == 'asm' or filetype == 'idb'):
        os.remove(filepath)
        print '[-] Clean ', filename
        return True

    return False 
Example 34
Project: malcode   Author: moonsea   File: getOpCodeNdisasm.py    GNU General Public License v3.0 5 votes vote down vote up
def checkFile(filepath):
    if os.path.exists(filepath):
        try:
            os.remove(filepath)
        except:
            print '[-] Delete error' 
Example 35
Project: malcode   Author: moonsea   File: dosgenasm.py    GNU General Public License v3.0 5 votes vote down vote up
def cleanFile(filename, filepath):
    filetype = filename.split('.')[-1]
    if (filetype == 'asm' or filetype == 'idb'):
        os.remove(filepath)
        print '[-] Clean ', filename
        return True

    # unpack file
    if (filetype == 'dump'):
        return False
    return True

    # return False 
Example 36
Project: malcode   Author: moonsea   File: benignasm.py    GNU General Public License v3.0 5 votes vote down vote up
def cleanFile(filename, filepath):
    filetype = filename.split('.')[-1]
    if (filetype == 'asm' or filetype == 'idb'):
        os.remove(filepath)
        print '[-] Clean ', filename
        return True

    return False 
Example 37
Project: invenio-openaire   Author: inveniosoftware   File: conftest.py    MIT License 5 votes vote down vote up
def db(app):
    """Setup database."""
    if not database_exists(str(db_.engine.url)):
        create_database(str(db_.engine.url))
    db_.create_all()
    yield db_
    db_.session.remove()
    db_.drop_all() 
Example 38
Project: invenio-openaire   Author: inveniosoftware   File: conftest.py    MIT License 5 votes vote down vote up
def sqlite_tmpdb():
    """Create a temporary sqlite database file."""
    fd, path = tempfile.mkstemp("_db.sqlite")

    yield path

    os.remove(path) 
Example 39
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_read_nonexisting(self):
        mediafile = self._mediafile_fixture('full')
        os.remove(mediafile.path)
        self.assertRaises(UnreadableFileError, MediaFile, mediafile.path) 
Example 40
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_save_nonexisting(self):
        mediafile = self._mediafile_fixture('full')
        os.remove(mediafile.path)
        try:
            mediafile.save()
        except UnreadableFileError:
            pass 
Example 41
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_delete_nonexisting(self):
        mediafile = self._mediafile_fixture('full')
        os.remove(mediafile.path)
        try:
            mediafile.delete()
        except UnreadableFileError:
            pass 
Example 42
Project: pyblish-win   Author: pyblish   File: main.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])
            else:
                raise ValueError('filename %s does not start with the '
                                 'input_base_dir %s' % (
                                         filename, self._input_base_dir))
        if self._append_suffix:
            filename += self._append_suffix
        if orig_filename != filename:
            output_dir = os.path.dirname(filename)
            if not os.path.isdir(output_dir):
                os.makedirs(output_dir)
            self.log_message('Writing converted %s to %s.', orig_filename,
                             filename)
        if not self.nobackups:
            # Make backup
            backup = filename + ".bak"
            if os.path.lexists(backup):
                try:
                    os.remove(backup)
                except os.error, err:
                    self.log_message("Can't remove backup %s", backup)
            try:
                os.rename(filename, backup)
            except os.error, err:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file 
Example 43
Project: pyblish-win   Author: pyblish   File: pytree_idempotency.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def diff(fn, tree):
    f = open("@", "w")
    try:
        f.write(str(tree))
    finally:
        f.close()
    try:
        return os.system("diff -u %s @" % fn)
    finally:
        os.remove("@") 
Example 44
Project: pyblish-win   Author: pyblish   File: test_parser.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def diff(fn, result, encoding):
    f = open("@", "w")
    try:
        f.write(result.encode(encoding))
    finally:
        f.close()
    try:
        fn = fn.replace('"', '\\"')
        return os.system('diff -u "%s" @' % fn)
    finally:
        os.remove("@") 
Example 45
Project: pyblish-win   Author: pyblish   File: transactions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        try:
            os.remove(get_db_path())
        except OSError:
            pass

        self.con1 = sqlite.connect(get_db_path(), timeout=0.1)
        self.cur1 = self.con1.cursor()

        self.con2 = sqlite.connect(get_db_path(), timeout=0.1)
        self.cur2 = self.con2.cursor() 
Example 46
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self):
        """
        Clean up this handler.

        You can remove the application name from the registry as a
        source of event log entries. However, if you do this, you will
        not be able to see the events as you intended in the Event Log
        Viewer - it needs to be able to access the registry to get the
        DLL name.
        """
        #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
        logging.Handler.close(self) 
Example 47
Project: pyblish-win   Author: pyblish   File: dir_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _build_cmdtuple(path, cmdtuples):
    """Helper for remove_tree()."""
    for f in os.listdir(path):
        real_f = os.path.join(path,f)
        if os.path.isdir(real_f) and not os.path.islink(real_f):
            _build_cmdtuple(real_f, cmdtuples)
        else:
            cmdtuples.append((os.remove, real_f))
    cmdtuples.append((os.rmdir, path)) 
Example 48
Project: pyblish-win   Author: pyblish   File: test_dep_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_newer_group(self):
        tmpdir = self.mkdtemp()
        sources = os.path.join(tmpdir, 'sources')
        os.mkdir(sources)
        one = os.path.join(sources, 'one')
        two = os.path.join(sources, 'two')
        three = os.path.join(sources, 'three')
        old_file = os.path.abspath(__file__)

        # return true if 'old_file' is out-of-date with respect to any file
        # listed in 'sources'.
        self.write_file(one)
        self.write_file(two)
        self.write_file(three)
        self.assertTrue(newer_group([one, two, three], old_file))
        self.assertFalse(newer_group([one, two, old_file], three))

        # missing handling
        os.remove(one)
        self.assertRaises(OSError, newer_group, [one, two, old_file], three)

        self.assertFalse(newer_group([one, two, old_file], three,
                                     missing='ignore'))

        self.assertTrue(newer_group([one, two, old_file], three,
                                    missing='newer')) 
Example 49
Project: pyblish-win   Author: pyblish   File: test_sysconfig.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def cleanup_testfn(self):
        path = test.test_support.TESTFN
        if os.path.isfile(path):
            os.remove(path)
        elif os.path.isdir(path):
            shutil.rmtree(path) 
Example 50
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_make_distribution(self):
        # now building a sdist
        dist, cmd = self.get_cmd()

        # creating a gztar then a tar
        cmd.formats = ['gztar', 'tar']
        cmd.ensure_finalized()
        cmd.run()

        # making sure we have two files
        dist_folder = join(self.tmp_dir, 'dist')
        result = os.listdir(dist_folder)
        result.sort()
        self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])

        os.remove(join(dist_folder, 'fake-1.0.tar'))
        os.remove(join(dist_folder, 'fake-1.0.tar.gz'))

        # now trying a tar then a gztar
        cmd.formats = ['tar', 'gztar']

        cmd.ensure_finalized()
        cmd.run()

        result = os.listdir(dist_folder)
        result.sort()
        self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])