Python shutil.copy() Examples

The following are code examples for showing how to use shutil.copy(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: python-   Author: secondtonone1   File: download.py    (license) View Source Project 7 votes vote down vote up
def _copy_file(filename, location, link):
    copy = True
    download_location = os.path.join(location, link.filename)
    if os.path.exists(download_location):
        response = ask_path_exists(
            'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)abort' %
            display_path(download_location), ('i', 'w', 'b', 'a'))
        if response == 'i':
            copy = False
        elif response == 'w':
            logger.warning('Deleting %s', display_path(download_location))
            os.remove(download_location)
        elif response == 'b':
            dest_file = backup_dir(download_location)
            logger.warning(
                'Backing up %s to %s',
                display_path(download_location),
                display_path(dest_file),
            )
            shutil.move(download_location, dest_file)
        elif response == 'a':
            sys.exit(-1)
    if copy:
        shutil.copy(filename, download_location)
        logger.info('Saved %s', display_path(download_location)) 
Example 2
Project: Telebackup   Author: LonamiWebs   File: backuper.py    (MIT License) View Source Project 6 votes vote down vote up
def backup_propic(self):
        """Backups the profile picture for the given
           entity as the current peer profile picture, returning its path"""

        # Allow multiple versions of the profile picture
        # TODO Maybe this should be another method, because when downloading media... We also have multiple versions
        filename = self.media_handler.get_propic_path(self.entity, allow_multiple=True)
        generic_filename = self.media_handler.get_propic_path(self.entity)
        if filename:  # User may not have a profile picture
            if not isfile(filename):
                # Only download the file if it doesn't exist yet
                self.client.download_profile_photo(self.entity.photo,
                                                   file_path=filename,
                                                   add_extension=False)
                # If we downloaded a new version, copy it to the "default" generic file
                if isfile(generic_filename):
                    remove(generic_filename)
                shutil.copy(filename, generic_filename)

            # The user may not have a profile picture
            return generic_filename 
Example 3
Project: my-first-blog   Author: AnkurBegining   File: download.py    (license) View Source Project 6 votes vote down vote up
def _copy_file(filename, location, link):
    copy = True
    download_location = os.path.join(location, link.filename)
    if os.path.exists(download_location):
        response = ask_path_exists(
            'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)abort' %
            display_path(download_location), ('i', 'w', 'b', 'a'))
        if response == 'i':
            copy = False
        elif response == 'w':
            logger.warning('Deleting %s', display_path(download_location))
            os.remove(download_location)
        elif response == 'b':
            dest_file = backup_dir(download_location)
            logger.warning(
                'Backing up %s to %s',
                display_path(download_location),
                display_path(dest_file),
            )
            shutil.move(download_location, dest_file)
        elif response == 'a':
            sys.exit(-1)
    if copy:
        shutil.copy(filename, download_location)
        logger.info('Saved %s', display_path(download_location)) 
Example 4
Project: rivalcfg   Author: flozz   File: setup.py    (Do What The F*ck You Want To Public License) View Source Project 6 votes vote down vote up
def run(self):
        _install.run(self)
        print("Installing udev rules...")
        if not os.path.isdir("/etc/udev/rules.d"):
            print("WARNING: udev rules have not been installed (/etc/udev/rules.d is not a directory)")
            return
        try:
            shutil.copy("./rivalcfg/data/99-steelseries-rival.rules", "/etc/udev/rules.d/")
        except IOError:
            print("WARNING: udev rules have not been installed (permission denied)")
            return
        try:
            subprocess.call(["udevadm", "trigger"])
        except OSError:
            print("WARNING: unable to update udev rules, please run the 'udevadm trigger' command")
            return
        print("Done!") 
Example 5
Project: cellranger   Author: 10XGenomics   File: bam.py    (license) View Source Project 6 votes vote down vote up
def concatenate(out_file_name, all_in_file_names):
    """ Concatenate a list of bam files into a final output file """

    # Filter out empty BAM files -- these cause samtools cat to generate
    # a BAM with a premature end block
    in_file_names = [f for f in all_in_file_names if not bam_is_empty(f)]

    if len(in_file_names) > 1:
        args = ['samtools', 'cat', '-o', out_file_name]
        args.extend(in_file_names)
        subprocess.check_call(args)
    elif len(in_file_names) == 0:
        # If all the BAMs are empty, just copy 1 over
        shutil.copy(all_in_file_names[0], out_file_name)
    else:
        shutil.copy(in_file_names[0], out_file_name) 
Example 6
Project: mbed-cli   Author: ARMmbed   File: mbed.py    (license) View Source Project 6 votes vote down vote up
def post_action(self):
        mbed_tools_path = self.get_tools_dir()

        if not mbed_tools_path and (self.is_classic or os.path.exists(os.path.join(self.path, Cfg.file))):
            self.add_tools(os.path.join(self.path, '.temp'))
            mbed_tools_path = self.get_tools_dir()

        if not mbed_tools_path:
            warning("Cannot find the mbed tools directory in \"%s\"" % self.path)
            return False

        if (not os.path.isfile(os.path.join(self.path, 'mbed_settings.py')) and
                os.path.isfile(os.path.join(mbed_tools_path, 'default_settings.py'))):
            shutil.copy(os.path.join(mbed_tools_path, 'default_settings.py'), os.path.join(self.path, 'mbed_settings.py'))

        self.check_requirements(True) 
Example 7
Project: otRebuilder   Author: Pal3love   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def copyFromReader(self, reader, sourcePath, destPath):
		"""
		Copy the sourcePath in the provided UFOReader to destPath
		in this writer. The paths must be relative. They may represent
		directories or paths. This uses the most memory efficient
		method possible for copying the data possible.
		"""
		if not isinstance(reader, UFOReader):
			raise UFOLibError("The reader must be an instance of UFOReader.")
		fullSourcePath = os.path.join(reader._path, sourcePath)
		if not reader._checkForFile(fullSourcePath):
			raise UFOLibError("No file named \"%s\" to copy from." % sourcePath)
		fullDestPath = os.path.join(self._path, destPath)
		if os.path.exists(fullDestPath):
			raise UFOLibError("A file named \"%s\" already exists." % sourcePath)
		self._buildDirectoryTree(destPath)
		if os.path.isdir(fullSourcePath):
			shutil.copytree(fullSourcePath, fullDestPath)
		else:
			shutil.copy(fullSourcePath, fullDestPath)

	# UFO mod time 
Example 8
Project: bob   Author: BobBuildTool   File: utils.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def summonMagic():
    import magic
    if hasattr(magic, 'from_file'):
        # https://pypi.python.org/pypi/python-magic
        return magic
    elif hasattr(magic, 'open'):
        # http://www.darwinsys.com/file/, in Debian as python3-magic
        class WrapMagic:
            def __init__(self):
                self.magic = magic.open(magic.NONE)
                self.magic.load()

            def from_file(self, name):
                return self.magic.file(name)
        return WrapMagic()
    else:
        raise NotImplementedError("I do not understand your magic")

### directory copy ### 
Example 9
Project: wr-lx-setup   Author: Wind-River   File: setup.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def load_layer_index(self):
        # Load Layer_Index

        # Check if we have a mirror-index, and load it if we do...
        mirror_index_path = self.load_mirror_index(self.base_url + '/mirror-index')

        # Mirror also has a copy of the associated XML bits
        if mirror_index_path:
            self.xml_dir = os.path.join(mirror_index_path, 'xml')

        # Setup replace strings as late as possible.  The various self.* values
        # may be modified prior to this place.
        replace = []
        replace = replace + settings.REPLACE
        replace = replace + [
                   ( '#INSTALL_DIR#', self.install_dir ),
                   ( '#BASE_URL#', self.base_url ),
                   ( '#BASE_BRANCH#', self.base_branch ),
                  ]

        self.index = Layer_Index(indexcfg=settings.INDEXES, base_branch=self.base_branch, replace=replace, mirror=mirror_index_path) 
Example 10
Project: QUANTAXIS   Author: yutiansut   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def sourcecpy(src, des):
    src = os.path.normpath(src)
    des = os.path.normpath(des)
    if not os.path.exists(src) or not os.path.exists(src):
        print("folder is not exist")
        sys.exit(1)
    # ?????????????????????????
    os.chdir(src)
    src_file = [os.path.join(src, file) for file in os.listdir()]
    for source in src_file:
        # ????
        if os.path.isfile(source):
            shutil.copy(source, des)  # ????????????????
        # ????
        if os.path.isdir(source):
            p, src_name = os.path.split(source)
            des = os.path.join(des, src_name)
            shutil.copytree(source, des)  # ??????????????????

# ??CLI????? 
Example 11
Project: NeoAnalysis   Author: neoanalysis   File: spikesorting.py    (license) View Source Project 6 votes vote down vote up
def __unitsNumChanged(self):
        if hasattr(self,"auto_result"):
            if self.autoSortThisCheck.isChecked():

                self.saveChannelCheck.setChecked(False)
                self.chnResultPool.pop(self.selectChan,None)

                self.units = self.auto_result.copy()
                self.units[self.units>int(self.unitsNumWgt.currentText())] = 0

                self.__draw_pk3()
                self.__update_pk3_roi()
                self.__draw_pk2()
                if self.pca_3d is True:
                    self.__draw_3D_PCA()

                
# The SpikeSorting class use this class to draw multiple lines quickly in a memory-efficient way. 
Example 12
Project: NeoAnalysis   Author: neoanalysis   File: spikesorting.py    (license) View Source Project 6 votes vote down vote up
def __unitsNumChanged(self):
        if hasattr(self,"auto_result"):
            if self.autoSortThisCheck.isChecked():

                self.saveChannelCheck.setChecked(False)
                self.chnResultPool.pop(self.selectChan,None)

                self.units = self.auto_result.copy()
                self.units[self.units>int(self.unitsNumWgt.currentText())] = 0

                self.__draw_pk3()
                self.__update_pk3_roi()
                self.__draw_pk2()
                if self.pca_3d is True:
                    self.__draw_3D_PCA()

                
# The SpikeSorting class use this class to draw multiple lines quickly in a memory-efficient way. 
Example 13
Project: Flask_Blog   Author: sugarguo   File: download.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _copy_file(filename, location, content_type, link):
    copy = True
    download_location = os.path.join(location, link.filename)
    if os.path.exists(download_location):
        response = ask_path_exists(
            'The file %s exists. (i)gnore, (w)ipe, (b)ackup ' %
            display_path(download_location), ('i', 'w', 'b'))
        if response == 'i':
            copy = False
        elif response == 'w':
            logger.warn('Deleting %s' % display_path(download_location))
            os.remove(download_location)
        elif response == 'b':
            dest_file = backup_dir(download_location)
            logger.warn('Backing up %s to %s'
                        % (display_path(download_location), display_path(dest_file)))
            shutil.move(download_location, dest_file)
    if copy:
        shutil.copy(filename, download_location)
        logger.notify('Saved %s' % display_path(download_location)) 
Example 14
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements.txt', requirements)
        args = ['-r', requirements]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated flask: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 15
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package_in_nested_requirements(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements-with-nested-reqfile.txt')
        requirements_nested = os.path.join(tempdir, 'requirements-nested.txt')
        shutil.copy('tests/samples/requirements-with-nested-reqfile.txt', requirements)
        shutil.copy('tests/samples/requirements-nested.txt', requirements_nested)
        args = ['-r', requirements]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'readtime'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated readtime: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package_in_nested_requirements').read()
            self.assertEquals(open(requirements).read(), expected_requirements)
            expected_requirements = open('tests/samples/results/test_updates_package_in_nested_requirements_nested').read()
            self.assertEquals(open(requirements_nested).read(), expected_requirements) 
Example 16
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_requirements_long_option_accepted(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements.txt', requirements)
        args = ['--requirement', requirements]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated flask: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 17
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_exit_code_from_no_updates(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-up-to-date.txt', requirements)
        args = ['-r', requirements, '--nonzero-exit-code']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertEqual(result.exception.code, 10)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 10)
            expected_requirements = open('tests/samples/results/test_updates_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 18
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_exit_code_from_nested_requirements_file(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements-with-nested-reqfile.txt')
        requirements_nested = os.path.join(tempdir, 'requirements-nested.txt')
        shutil.copy('tests/samples/requirements-with-nested-reqfile.txt', requirements)
        shutil.copy('tests/samples/requirements-nested.txt', requirements_nested)
        args = ['-r', requirements, '--nonzero-exit-code']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'readtime'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertEqual(result.exception.code, 11)
            expected_output = "Updated readtime: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 11)
            expected_requirements = open('tests/samples/results/test_updates_package_in_nested_requirements').read()
            self.assertEquals(open(requirements).read(), expected_requirements)
            expected_requirements = open('tests/samples/results/test_updates_package_in_nested_requirements_nested').read()
            self.assertEquals(open(requirements_nested).read(), expected_requirements) 
Example 19
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_no_recursive_option(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements-with-nested-reqfile.txt')
        requirements_nested = os.path.join(tempdir, 'requirements-nested.txt')
        shutil.copy('tests/samples/requirements-with-nested-reqfile.txt', requirements)
        shutil.copy('tests/samples/requirements-nested.txt', requirements_nested)
        args = ['-r', requirements, '-n']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'readtime'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)

            expected_requirements = open('tests/samples/requirements-with-nested-reqfile.txt').read()
            self.assertEquals(open(requirements).read(), expected_requirements)
            expected_requirements = open('tests/samples/requirements-nested.txt').read()
            self.assertEquals(open(requirements_nested).read(), expected_requirements) 
Example 20
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_skip_package(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-multiple.txt', requirements)
        args = ['-r', requirements, '-s', 'flask']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated Alembic: 0.9 -> 0.10.1\nUpdated sqlalchemy: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_skip_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 21
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_skip_multiple_packages(self):
        requirements = 'tests/samples/requirements-multiple.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile, '-s', 'flask, alembic , SQLAlchemy']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open(requirements).read()
            self.assertEquals(open(tmpfile).read(), expected_requirements) 
Example 22
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_only(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-multiple.txt', requirements)
        args = ['-r', requirements, '--only', 'flask']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated flask: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_only').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 23
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package_with_no_version_specified(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements.txt', requirements)
        args = ['-r', requirements, '-f']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated flask: 0.9 -> 0.10.1\nUpdated flask: Unknown -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package_with_no_version_specified').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 24
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_invalid_package(self):
        requirements = 'tests/samples/requirements.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            mock_find_all_candidates.return_value = []

            result = self.runner.invoke(pur, args)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertIsNone(result.exception)
            self.assertEquals(result.exit_code, 0)
            self.assertEquals(open(tmpfile).read(), open(requirements).read()) 
Example 25
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_no_arguments(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements.txt', requirements)
        args = []

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            with self.cd(tempdir):
                result = self.runner.invoke(pur, args)

            self.assertIsNone(result.exception)
            expected_output = "Updated flask: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 26
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package_with_number_in_name(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-version-in-name.txt', requirements)
        args = ['-r', requirements]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'package1'
            version = '2.0'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated package1: 1 -> 2.0\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package_with_version_in_name').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 27
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package_with_extras(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-with-extras.txt', requirements)
        args = ['-r', requirements]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'firstpackage'
            version = '2.0'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            expected_output = "Updated firstpackage1: 1 -> 2.0\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertIsNone(result.exception)
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package_with_extras').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 28
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_max_version_spec_prevents_updating_package(self):
        requirements = 'tests/samples/requirements-with-max-version-spec.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'afakepackage'
            version = '2.0'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open(tmpfile).read()
            self.assertEquals(open(tmpfile).read(), expected_requirements) 
Example 29
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_notequal_version_spec_prevents_updating_package(self):
        requirements = 'tests/samples/requirements-multiline.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'afakepackage'
            version = '0.9.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open(tmpfile).read()
            self.assertEquals(open(tmpfile).read(), expected_requirements) 
Example 30
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package_with_multiline_spec(self):
        requirements = 'tests/samples/requirements-multiline.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'afakepackage'
            version = '1.0'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "Updated afakepackage: 0.9 -> 1.0\nUpdated afakepackage: 0.9 -> 1.0\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package_with_multiline_spec').read()
            self.assertEquals(open(tmpfile).read(), expected_requirements) 
Example 31
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_does_not_update_package_with_multiline_spec(self):
        requirements = 'tests/samples/requirements-multiline.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'afakepackage'
            version = '1.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = "All requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open(requirements).read()
            self.assertEquals(open(tmpfile).read(), expected_requirements) 
Example 32
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_updates_package_with_min_version_spec(self):
        requirements = 'tests/samples/requirements-with-min-version-spec.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile]

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'django'
            version = '1.8.13'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            expected_output = "Updated django: 1.8.6 -> 1.8.13\nNew version for django found (1.8.13), but current spec prohibits updating: django > 1.8.6, < 1.9\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertIsNone(result.exception)
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package_with_min_version_spec').read()
            self.assertEquals(open(tmpfile).read(), expected_requirements) 
Example 33
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_dry_run(self):
        requirements = 'tests/samples/requirements.txt'
        tempdir = tempfile.mkdtemp()
        tmpfile = os.path.join(tempdir, 'requirements.txt')
        shutil.copy(requirements, tmpfile)
        args = ['-r', tmpfile, '-d']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)
            self.assertIsNone(result.exception)
            expected_output = '==> ' + tmpfile + ' <==\n' + \
                open('tests/samples/results/test_updates_package').read() + "\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            self.assertEquals(open(tmpfile).read(), open(requirements).read()) 
Example 34
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_interactive_choice_default(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements.txt', requirements)
        args = ['-r', requirements, '-i']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args)

            self.assertIsNone(result.exception)
            expected_output = "Update flask from 0.9 to 0.10.1? (y, n, q) [y]: \nUpdated flask: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 35
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_interactive_choice_yes(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements.txt', requirements)
        args = ['-r', requirements, '-i']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args, input='y\n')

            self.assertIsNone(result.exception)
            expected_output = "Update flask from 0.9 to 0.10.1? (y, n, q) [y]: y\nUpdated flask: 0.9 -> 0.10.1\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_updates_package').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 36
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_interactive_choice_quit(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-multiple.txt', requirements)
        args = ['-r', requirements, '-i']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args, input='y\nq\n')
            self.assertIsNone(result.exception)
            expected_output = "Update flask from 0.9 to 0.10.1? (y, n, q) [y]: y\nUpdated flask: 0.9 -> 0.10.1\nUpdate Alembic from 0.9 to 0.10.1? (y, n, q) [y]: q\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_interactive_choice_quit').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 37
Project: pip-update-requirements   Author: alanhamlett   File: test_pur.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def test_interactive_choice_invalid(self):
        tempdir = tempfile.mkdtemp()
        requirements = os.path.join(tempdir, 'requirements.txt')
        shutil.copy('tests/samples/requirements-multiple.txt', requirements)
        args = ['-r', requirements, '-i']

        with utils.mock.patch('pip._internal.index.PackageFinder.find_all_candidates') as mock_find_all_candidates:
            project = 'flask'
            version = '0.10.1'
            link = Link('')
            candidate = InstallationCandidate(project, version, link)
            mock_find_all_candidates.return_value = [candidate]

            result = self.runner.invoke(pur, args, input='z\nn\ny\nq\n')
            self.assertIsNone(result.exception)
            expected_output = "Update flask from 0.9 to 0.10.1? (y, n, q) [y]: z\nPlease enter either y, n, q.\nUpdate flask from 0.9 to 0.10.1? (y, n, q) [y]: n\nUpdate Alembic from 0.9 to 0.10.1? (y, n, q) [y]: y\nUpdated Alembic: 0.9 -> 0.10.1\nUpdate sqlalchemy from 0.9 to 0.10.1? (y, n, q) [y]: q\nAll requirements up-to-date.\n"
            self.assertEquals(u(result.output), u(expected_output))
            self.assertEquals(result.exit_code, 0)
            expected_requirements = open('tests/samples/results/test_interactive_choice_invalid').read()
            self.assertEquals(open(requirements).read(), expected_requirements) 
Example 38
Project: pip-update-requirements   Author: alanhamlett   File: download.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def _copy_file(filename, location, link):
    copy = True
    download_location = os.path.join(location, link.filename)
    if os.path.exists(download_location):
        response = ask_path_exists(
            'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)abort' %
            display_path(download_location), ('i', 'w', 'b', 'a'))
        if response == 'i':
            copy = False
        elif response == 'w':
            logger.warning('Deleting %s', display_path(download_location))
            os.remove(download_location)
        elif response == 'b':
            dest_file = backup_dir(download_location)
            logger.warning(
                'Backing up %s to %s',
                display_path(download_location),
                display_path(dest_file),
            )
            shutil.move(download_location, dest_file)
        elif response == 'a':
            sys.exit(-1)
    if copy:
        shutil.copy(filename, download_location)
        logger.info('Saved %s', display_path(download_location)) 
Example 39
Project: X1-Sync   Author: Kriegbaum   File: X1_sync.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setup():                                                                    #Asks new user for information
    print('Enter the directory for your iTunes library')
    spacer_small()
    print('This is typically stored in your \'user/Music/iTunes\' folder')
    print('You can also make a copy wherever you want in iTunes')
    print('Just go File>Library>Export Library...')
    tunes_library_path = input()                                                #Where is my itunes library?
    spacer()
    print('Now you gotta give me the root directory for your media player')
    print('This is typically /Volumes/YOUR DEVICE NAME')
    fiio_dir = input()                                                          #Device directory
    if fiio_dir[len(fiio_dir) - 1] == '/':
        fiio_dir = fiio_dir[0: len(fiio_dir) - 1]                               #User may add an extra slash, get rid of it
    spacer()
    print('Ima save those settings')
    settings_body = 'iTunes Library Path:\n' + tunes_library_path + '\n' + 'Device Root Directory\n' + fiio_dir
    newsettings = open(fiio_dir + '/X1_sync_settings.txt', 'w')                 #Write a settings file into the root directory of device
    newsettings.write(settings_body)
    newsettings.close()
    return [tunes_library_path, fiio_dir] 
Example 40
Project: code   Author: ActiveState   File: recipe-576844.py    (MIT License) View Source Project 6 votes vote down vote up
def Dumpfile(): 
    fv.write('##########')
    fv.write('\n')
    fv.write("local Administrators on machine ")
    fv.write(host)
    fv.write(" are : ....\n\n")
    result,t,r= NetLocalGroupGetMembers(None,"Administrators",1)
    for item in result:
        fv.write(str(item))
        fv.write('\n')
    fv.write('\n\n')
    fv.write ("##########\n")
    fv.write('the following software is installed on ')
    fv.write(host)
    fv.write(': .... \n\n')
    listofsoft=readSubKeys("HKLM", "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
    listofsoft.sort()
    for software in listofsoft:
        fv.write(str(software))
        fv.write('\n')
    fv.close()
    shutil.copy(srcfile,r"\\10.1.1.12\gms")
    win32api.DeleteFile(srcfile) 
Example 41
Project: mbin   Author: fanglab   File: mbin.py    (license) View Source Project 6 votes vote down vote up
def cat_contig_files_from_subprocs( tup ):
	contig    = tup[0]
	tmp       = tup[1]
	j         = tup[2]
	N_contigs = tup[3]
	logging.info("...contig %s (%s/%s)" % (contig, j, N_contigs))
	contig_fns = glob.glob( os.path.join(tmp, "chunk_*", "%s_*.tmp" % contig) )
	ftypes = set( map(lambda x: os.path.basename(x).split("_")[-1], contig_fns) )
	for ftype in ftypes:
		if ftype in ["compkmers.tmp", "ipdskmers.tmp"]:
			first_fn = glob.glob( os.path.join(tmp, "chunk_*", "%s_%s" % (contig, ftype)) )[0]
			shutil.copy( first_fn, os.path.join(tmp, "%s_%s" % (contig,ftype)))
		else:
			to_cat  = glob.glob( os.path.join(tmp, "chunk_*", "%s_%s" % (contig, ftype)) )
			to_cat.sort()
			outname = os.path.join(tmp, "%s_%s" % (contig,ftype) )
			cat_list_of_files(to_cat, outname, del_ins=False) 
Example 42
Project: molmaker   Author: mnmelo   File: molmaker.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def minimize(self):
        self.tpr = "%s.tpr" % (self.basename)
        self.mdout = "%s.out.mdp" % (self.basename)
        self.pplog = "%s.pp.log" % (self.basename)
        self.deffnm = "%s.md" % (self.basename)
        self.mdgro = "%s.gro" % (self.deffnm)
        self.mdtrr = "%s.trr" % (self.deffnm)
        self.mdlog = "%s.log" % (self.deffnm)
        self.mdedr = "%s.edr" % (self.deffnm)

        ppargs = self.grompp + ["-f",self.mdp, "-p",self.top, "-c",self.gro, "-maxwarn","3", "-po",self.mdout, "-o",self.tpr]
        mdargs = self.mdrun + ["-s",self.tpr, "-nt","1", "-deffnm",self.deffnm, "-cpt","0"]

        with open(self.pplog, "w") as pplog:
            md_env = os.environ.copy()
            md_env["GMX_SUPPRESS_DUMP"] = '1'
            md_env["GMX_MAXBACKUP"] = '-1'
            pp = subprocess.call(ppargs, stdout=pplog, stderr=pplog, env=md_env)
        if pp:
            sys.stderr.write("grompp error: check %s\n" % (self.pplog))
            sys.exit()
        md = subprocess.call(mdargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=md_env)
        if md:
            sys.stderr.write("mdrun error: check %s\n" % (self.mdlog))
            sys.exit() 
Example 43
Project: charm-keystone   Author: openstack   File: keystone_utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def assess_status_func(configs):
    """Helper function to create the function that will assess_status() for
    the unit.
    Uses charmhelpers.contrib.openstack.utils.make_assess_status_func() to
    create the appropriate status function and then returns it.
    Used directly by assess_status() and also for pausing and resuming
    the unit.

    NOTE: REQUIRED_INTERFACES is augmented with the optional interfaces
    depending on the current config before being passed to the
    make_assess_status_func() function.

    @param configs: a templating.OSConfigRenderer() object
    @return f() -> None : a function that assesses the unit's workload status
    """
    required_interfaces = REQUIRED_INTERFACES.copy()
    required_interfaces.update(get_optional_interfaces())
    return make_assess_status_func(
        configs, required_interfaces,
        charm_func=check_optional_relations,
        services=services(),
        ports=determine_ports()) 
Example 44
Project: charm-keystone   Author: openstack   File: keystone_utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def assess_status_func(configs):
    """Helper function to create the function that will assess_status() for
    the unit.
    Uses charmhelpers.contrib.openstack.utils.make_assess_status_func() to
    create the appropriate status function and then returns it.
    Used directly by assess_status() and also for pausing and resuming
    the unit.

    NOTE: REQUIRED_INTERFACES is augmented with the optional interfaces
    depending on the current config before being passed to the
    make_assess_status_func() function.

    @param configs: a templating.OSConfigRenderer() object
    @return f() -> None : a function that assesses the unit's workload status
    """
    required_interfaces = REQUIRED_INTERFACES.copy()
    required_interfaces.update(get_optional_interfaces())
    return make_assess_status_func(
        configs, required_interfaces,
        charm_func=check_optional_relations,
        services=services(),
        ports=determine_ports()) 
Example 45
Project: SoCFoundationFlow   Author: mattaw   File: build_logs.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def exit_cleanup():
	try:
		fileobj = sys.stdout.fileobj
	except AttributeError:
		pass
	else:
		sys.stdout.is_valid = False
		sys.stderr.is_valid = False
		fileobj.close()
		filename = sys.stdout.filename

		Logs.info('Output logged to %r' % filename)

		# then copy the log file to "latest.log" if possible
		up = os.path.dirname(os.path.abspath(filename))
		try:
			shutil.copy(filename, os.path.join(up, 'latest.log'))
		except OSError:
			# this may fail on windows due to processes spawned
			# 
			pass 
Example 46
Project: SoCFoundationFlow   Author: mattaw   File: build_logs.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def exit_cleanup():
	try:
		fileobj = sys.stdout.fileobj
	except AttributeError:
		pass
	else:
		sys.stdout.is_valid = False
		sys.stderr.is_valid = False
		fileobj.close()
		filename = sys.stdout.filename

		Logs.info('Output logged to %r' % filename)

		# then copy the log file to "latest.log" if possible
		up = os.path.dirname(os.path.abspath(filename))
		try:
			shutil.copy(filename, os.path.join(up, 'latest.log'))
		except OSError:
			# this may fail on windows due to processes spawned
			# 
			pass 
Example 47
Project: SoCFoundationFlow   Author: mattaw   File: build_logs.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def exit_cleanup():
	try:
		fileobj = sys.stdout.fileobj
	except AttributeError:
		pass
	else:
		sys.stdout.is_valid = False
		sys.stderr.is_valid = False
		fileobj.close()
		filename = sys.stdout.filename

		Logs.info('Output logged to %r' % filename)

		# then copy the log file to "latest.log" if possible
		up = os.path.dirname(os.path.abspath(filename))
		try:
			shutil.copy(filename, os.path.join(up, 'latest.log'))
		except OSError:
			# this may fail on windows due to processes spawned
			# 
			pass 
Example 48
Project: TACTIC-Handler   Author: listyque   File: client_api_test.py    (Eclipse Public License 1.0) View Source Project 6 votes vote down vote up
def _test_checkin_with_handoff(my):

        search_type = "unittest/person"
        code = "joe"
        search_key = my.server.build_search_key(search_type, code)

        # copy file to handoff dir
        path = "%s/test/miso_ramen.jpg" % my.client_lib_dir
        handoff_dir = my.server.get_handoff_dir()
        shutil.copy(path, handoff_dir)

        # check the file in
        snapshot = my.server.simple_checkin(search_key, "publish", path, use_handoff_dir=True)
        snapshot_code = snapshot.get("code")

        # get the filename
        file_type = "main"
        path = my.server.get_path_from_snapshot(snapshot_code, file_type)
        exists = os.path.exists(path)
        my.assertEquals(True, exists)

        # check that the file name is correct
        filename = os.path.basename(path)
        # changed naming.. adds "publish"
        my.assertEquals("miso_ramen_publish_v001.jpg", filename) 
Example 49
Project: evaluation_tools   Author: JSALT-Rosetta   File: generate_features.py    (license) View Source Project 6 votes vote down vote up
def mean_variance_normalisation(h5f, mvn_h5f, vad=None):
    """Do mean variance normlization. Optionnaly use a vad.

    Parameters:
    ----------
    h5f: str. h5features file name
    mvn_h5f: str, h5features output name
    """
    dset = h5py.File(h5f).keys()[0]
    if vad is not None:
        raise NotImplementedError
    else:
        data = h5py.File(h5f)[dset]['features'][:]
        features = data
    epsilon = np.finfo(data.dtype).eps
    mean = np.mean(data)
    std = np.std(data)
    mvn_features = (features - mean) / (std + epsilon)
    shutil.copy(h5f, mvn_h5f)
    h5py.File(mvn_h5f)[dset]['features'][:] = mvn_features 
Example 50
Project: swjtu-pyscraper   Author: Desgard   File: download.py    (MIT License) View Source Project 6 votes vote down vote up
def _copy_file(filename, location, link):
    copy = True
    download_location = os.path.join(location, link.filename)
    if os.path.exists(download_location):
        response = ask_path_exists(
            'The file %s exists. (i)gnore, (w)ipe, (b)ackup ' %
            display_path(download_location), ('i', 'w', 'b'))
        if response == 'i':
            copy = False
        elif response == 'w':
            logger.warning('Deleting %s', display_path(download_location))
            os.remove(download_location)
        elif response == 'b':
            dest_file = backup_dir(download_location)
            logger.warning(
                'Backing up %s to %s',
                display_path(download_location),
                display_path(dest_file),
            )
            shutil.move(download_location, dest_file)
    if copy:
        shutil.copy(filename, download_location)
        logger.info('Saved %s', display_path(download_location))