Python stat 模块,S_IEXEC 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用stat.S_IEXEC

项目:django-zerodowntime    作者:rentlytics    | 项目源码 | 文件源码
def handle(self, *args, **options):
        commit_msg_path = os.path.join(self.HOOK_PATH, 'commit-msg')

        hook_exists = os.path.exists(commit_msg_path)

        if hook_exists:
            with open(commit_msg_path, 'r') as fp:
                hook_content = fp.read()
        else:
            hook_content = '#!/usr/bin/env bash\n\n'

        if 'ZERODOWNTIME_COMMIT_MSG_HOOK' not in hook_content:
            hook_content += COMMIT_MSG_HOOK

            with open(commit_msg_path, 'w') as fp:
                fp.write(hook_content)

            st = os.stat(commit_msg_path)
            os.chmod(commit_msg_path, st.st_mode | stat.S_IEXEC)
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def _clean_upgrade(binary_ok, binary_path, path, temp_path):
    if binary_ok:
        import stat
        # save the permissions from the current binary
        old_stat = os.stat(binary_path)
        # rename the current binary in order to replace it with the latest
        os.rename(binary_path, path + "/old")
        os.rename(temp_path, binary_path)
        # set the same permissions that had the previous binary
        os.chmod(binary_path, old_stat.st_mode | stat.S_IEXEC)
        # delete the old binary
        os.remove(path + "/old")
        print("mongoaudit updated, restarting...")
        os.execl(binary_path, binary_path, *sys.argv)
    else:
        os.remove(temp_path)
        print("couldn't download the latest binary")
项目:kudubot    作者:namboy94    | 项目源码 | 文件源码
def download_executable(self):
        """
        Downloads the executable file

        :return: None
        """
        # noinspection PyBroadException
        try:
            self.logger.info("Downloading executable file")
            with open(self.executable_file, 'wb') as destination:
                data = requests.get(self.define_executable_file_url()).content
                destination.write(data)
            self.logger.info("Download Complete")

            # Set executable permissions
            st = os.stat(self.executable_file)
            os.chmod(self.executable_file, st.st_mode | stat.S_IEXEC)

        except Exception as e:
            self.logger.error(
                "Could not download executable. Disabling Service.")
            self.logger.debug("Cause of download failure: " + str(e))
            if os.path.isfile(self.executable_file):
                os.remove(self.executable_file)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def run(last_run_version):
    if config.get(["modules", "launcher", "auto_start"], 0):
        import autorun
        autorun.enable()

    if os.path.isdir(os.path.join(top_path, 'launcher')):
        shutil.rmtree(os.path.join(top_path, 'launcher')) # launcher is for auto-update from 2.X

    if older_or_equal(last_run_version, '3.0.4'):
        xlog.info("migrating to 3.x.x")
        for filename in os.listdir(top_path):
            filepath = os.path.join(top_path, filename)
            if os.path.isfile(filepath):
                if sys.platform != 'win32' and filename == 'start':
                    st = os.stat(filepath)
                    os.chmod(filepath, st.st_mode | stat.S_IEXEC)
                if filename in ['start.sh', 'start.command', 'start.lnk', 'LICENSE.txt', 'download.md', 'version.txt', 'xxnet', 'xxnet.bat', 'xxnet.vbs', 'xx_net.sh']:
                    os.remove(filepath)
            else:
                if filename in ['goagent', 'python27', 'gae_proxy', 'php_proxy', 'x_tunnel', 'python3', 'Python3', 'lib', 'SwitchySharp']:
                    shutil.rmtree(filepath)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def run(last_run_version):
    if config.get(["modules", "launcher", "auto_start"], 0):
        import autorun
        autorun.enable()

    if os.path.isdir(os.path.join(top_path, 'launcher')):
        shutil.rmtree(os.path.join(top_path, 'launcher')) # launcher is for auto-update from 2.X

    if older_or_equal(last_run_version, '3.0.4'):
        xlog.info("migrating to 3.x.x")
        for filename in os.listdir(top_path):
            filepath = os.path.join(top_path, filename)
            if os.path.isfile(filepath):
                if sys.platform != 'win32' and filename == 'start':
                    st = os.stat(filepath)
                    os.chmod(filepath, st.st_mode | stat.S_IEXEC)
                if filename in ['start.sh', 'start.command', 'start.lnk', 'LICENSE.txt', 'download.md', 'version.txt', 'xxnet', 'xxnet.bat', 'xxnet.vbs', 'xx_net.sh']:
                    os.remove(filepath)
            else:
                if filename in ['goagent', 'python27', 'gae_proxy', 'php_proxy', 'x_tunnel', 'python3', 'Python3', 'lib', 'SwitchySharp']:
                    shutil.rmtree(filepath)
项目:lover    作者:jerluc    | 项目源码 | 文件源码
def get(env, platform=None):
    if not platform:
        platform = env.platform
    # Only try to download/extract if it doesn't already exist
    if not os.path.exists(env.love_binary(platform=platform)):
        # Only try to download if the .zip doesn't already exist
        if not os.path.exists(env.download_file(platform=platform)):
            print('Downloading LOVE (%s; %s)...' %
                    (env.conf.love_version, platform))
            download(env.download_url(platform=platform),
                    env.download_file(platform=platform))
            print('Download complete!')
        print('Extracting LOVE (%s; %s)...' % (env.conf.love_version,
            platform))
        extract(platform, env.download_file(platform=platform))
        st = os.stat(env.love_binary(platform=platform))
        os.chmod(env.love_binary(platform=platform),
                st.st_mode | stat.S_IEXEC)
        print('Extraction complete!')
项目:cadee    作者:kamerlinlab    | 项目源码 | 文件源码
def to_disk(self, path=None, name=None):
        """read from ram, overwrite disk"""
        if not self._inram:
            raise Exception('Not in ram. Cant write to disk.')
        if path is None:
            path = self.path
        if name is None:
            name = self.name
        if not os.path.isdir(path):
            os.makedirs(path)
        with cd(path):
            with open(name, 'wb') as fil_out:
                fil_out.write(self.data)
            if self.executable:
                os.chmod(self.name, stat.S_IEXEC)
        self._ondisk = True
项目:mongoaudit    作者:stampery    | 项目源码 | 文件源码
def _clean_upgrade(binary_ok, binary_path, path, temp_path):
    if binary_ok:
        import stat
        # save the permissions from the current binary
        old_stat = os.stat(binary_path)
        # rename the current binary in order to replace it with the latest
        os.rename(binary_path, path + "/old")
        os.rename(temp_path, binary_path)
        # set the same permissions that had the previous binary
        os.chmod(binary_path, old_stat.st_mode | stat.S_IEXEC)
        # delete the old binary
        os.remove(path + "/old")
        print("mongoaudit updated, restarting...")
        os.execl(binary_path, binary_path, *sys.argv)
    else:
        os.remove(temp_path)
        print("couldn't download the latest binary")
项目:tm    作者:tulians    | 项目源码 | 文件源码
def copy_menu():
    """Copies interactive menu to the executable directory."""
    menu_source_path = source_directory + "/menu.py"
    menu_bin_path = executable_directory + "/tm"
    try:
        if not os.path.exists(executable_directory):
            os.makedirs(executable_directory)
        # Create a new file 'tm' in the executable directory.
        copyfile(menu_source_path, menu_bin_path)
        # Make the file executable.
        st = os.stat(menu_bin_path)
        os.chmod(menu_bin_path, st.st_mode | stat.S_IEXEC)
        print("Menu successfully copied to {}.".format(executable_directory))
        return True
    except IOError as detail:
        print("Menu file could not be copied to {}. ".
              format(executable_directory) + str(detail))
        return False
项目:unicorn-hat-hd    作者:pimoroni    | 项目源码 | 文件源码
def save(filename):
    try:
        os.mkdir('saves/')
    except OSError:
        pass
    try:
        data = unicorn.get_pixels()
        print(filename, data)
        file = open('saves/' + filename + '.py', 'w')
        file.write('#!/usr/bin/env python\n')
        file.write('import unicornhat, signal\n')
        file.write('pixels = ' + str(unicorn.get_pixels()) + '\n')
        file.write('unicornhat.set_pixels(pixels)\n')
        file.write('unicornhat.show()\n')
        file.write('signal.pause()')
        file.close()
        os.chmod('saves/' + filename + '.py', 0o777 | stat.S_IEXEC)

        return("ok" + str(unicorn.get_pixels()))
    except AttributeError:
        print("Unable to save, please update")
        print("unicornhat library!")
        return("fail")
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def run(last_run_version):
    if config.get(["modules", "launcher", "auto_start"], 0):
        import autorun
        autorun.enable()

    if os.path.isdir(os.path.join(top_path, 'launcher')):
        shutil.rmtree(os.path.join(top_path, 'launcher')) # launcher is for auto-update from 2.X

    if older_or_equal(last_run_version, '3.0.4'):
        xlog.info("migrating to 3.x.x")
        for filename in os.listdir(top_path):
            filepath = os.path.join(top_path, filename)
            if os.path.isfile(filepath):
                if sys.platform != 'win32' and filename == 'start':
                    st = os.stat(filepath)
                    os.chmod(filepath, st.st_mode | stat.S_IEXEC)
                if filename in ['start.sh', 'start.command', 'start.lnk', 'LICENSE.txt', 'download.md', 'version.txt', 'xxnet', 'xxnet.bat', 'xxnet.vbs', 'xx_net.sh']:
                    os.remove(filepath)
            else:
                if filename in ['goagent', 'python27', 'gae_proxy', 'php_proxy', 'x_tunnel', 'python3', 'Python3', 'lib', 'SwitchySharp']:
                    shutil.rmtree(filepath)
项目:buildroot    作者:flutter    | 项目源码 | 文件源码
def CopyTool(source_path):
  """Copies the given tool to the current directory, including a warning not
  to edit it."""
  with open(source_path) as source_file:
    tool_source = source_file.readlines()

  # Add header and write it out to the current directory (which should be the
  # root build dir).
  out_path = 'gyp-mac-tool'
  with open(out_path, 'w') as tool_file:
    tool_file.write(''.join([tool_source[0],
                             '# Generated by setup_toolchain.py do not edit.\n']
                            + tool_source[1:]))
  st = os.stat(out_path)
  os.chmod(out_path, st.st_mode | stat.S_IEXEC)

# Find the tool source, it's the first argument, and copy it.
项目:HPCinstall    作者:NCAR    | 项目源码 | 文件源码
def execute_installscript(options, files_to_archive, module_use):
    current_perm = os.stat(options.install_script.name)
    if not options.csgteam:   # too often this fail for csgteam
        os.chmod(options.install_script.name, current_perm.st_mode | stat.S_IEXEC)
    print term.bold_green("Running ./" + options.install_script.name + "...")
    stop_logging_current_session()                                  # log the output of the script in a different dir
    log = "hpci." + os.path.basename(options.install_script.name)  + "-" + str(
     datetime.datetime.now().isoformat().split(".")[0].replace("-", "").replace(":", "")) + ".log" #  20161116T114145
    start_logging_current_session(files_to_archive, log=log)
    p = subcall(module_use + "./" + options.install_script.name, use_popen=True, debug=options.debug)
    process_output = " "
    while process_output != "":               # continue while the process is running, it'll be "" when EOF is reached
        process_output = p.stdout.readline()  # needs to do this instead of using subprocess.call to allow 
        print process_output,                 # 'tee' to log the process output
    p.wait()
    stop_logging_current_session()
    files_to_archive.append(log)
    start_logging_current_session(files_to_archive, continuation=True)
    print term.bold_green("Done running ./" + options.install_script.name + " - exited with code " + str(p.returncode))
    if p.returncode != 0:
        ask_confirmation_for(True, "Running " + options.install_script.name + " failed. Archive logs anyway? ")
    files_to_archive.append(options.install_script.name)
项目:sultan    作者:aeroxis    | 项目源码 | 文件源码
def setUp(self):

        content = """
#!/usr/bin/env bash

OUTPUT_FILENAME=/tmp/SultanRunScript/lorum.txt
mkdir -p /tmp/SultanRunScript
echo 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n' > $OUTPUT_FILENAME 
echo 'Nunc in enim dictum, consectetur ex vehicula, fermentum orci.\n' > $OUTPUT_FILENAME
echo 'Donec sapien turpis, mattis vel urna sed, iaculis aliquam purus.\n' > $OUTPUT_FILENAME 
        """
        self.dir_path = '/tmp/SultanRunScript'
        self.script_filepath = '/tmp/SultanRunScript/myscript'
        self.output_filepath = '/tmp/SultanRunScript/lorum.txt'
        if os.path.exists(self.dir_path): shutil.rmtree(self.dir_path)

        s = Sultan()
        os.mkdir(self.dir_path)
        with open(self.script_filepath, 'w') as f:
            f.write(content)
        st = os.stat(self.script_filepath)
        os.chmod(self.script_filepath, st.st_mode | stat.S_IEXEC)
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def run(last_run_version):
    if config.get(["modules", "launcher", "auto_start"], 0):
        import autorun
        autorun.enable()

    if os.path.isdir(os.path.join(top_path, 'launcher')):
        shutil.rmtree(os.path.join(top_path, 'launcher')) # launcher is for auto-update from 2.X

    if older_or_equal(last_run_version, '3.0.4'):
        xlog.info("migrating to 3.x.x")
        for filename in os.listdir(top_path):
            filepath = os.path.join(top_path, filename)
            if os.path.isfile(filepath):
                if sys.platform != 'win32' and filename == 'start':
                    st = os.stat(filepath)
                    os.chmod(filepath, st.st_mode | stat.S_IEXEC)
                if not filename.startswith('.') and filename not in ['README.md', 'start', 'start.bat', 'start.vbs']:
                    os.remove(filepath)
            else:
                if not filename.startswith('.') and filename not in ['code', 'data']:
                    shutil.rmtree(filepath)
项目:start_jupyter_cm    作者:hyperspy    | 项目源码 | 文件源码
def add_jupyter_here():
    if not os.path.exists(NPATH):
        print("Nothing done. Currently only Gnome with Nautilus as file ",
              "manager is supported.")
        return
    if not os.path.exists(SPATH):
        os.makedirs(SPATH)

    logo_path = os.path.expandvars(os.path.join(
        os.path.dirname(__file__), 'icons'))
    logos = {'qtconsole': os.path.join(logo_path, 'jupyter-qtconsole.png'),
             'notebook': os.path.join(logo_path, 'jupyter.png')}
    for terminal in ["qtconsole", "notebook"]:
        script_path = os.path.join(SPATH, "Jupyter %s here" % terminal)
        if not os.path.exists(script_path):
            with open(script_path, "w") as f:
                f.write(script % (terminal, terminal))
            st = os.stat(script_path)
            os.chmod(script_path, st.st_mode | stat.S_IEXEC)
            call(['gio', 'set', '-t', 'string', '%s' % script_path,
                  'metadata::custom-icon', 'file://%s' % logos[terminal]])
            print('Jupyter %s here created.' % terminal)
项目:s2e-env    作者:S2E    | 项目源码 | 文件源码
def render_template(context, template, path=None, executable=False):
    """
    Renders the ``template`` template with the given ``context``. The result is
    written to ``path``. If ``path`` is not specified, the result is
    returned as a string
    """
    env = _init_template_env()
    data = env.get_template(template).render(context)

    if not path:
        return data

    with open(path, 'w') as f:
        f.write(data)

    if executable:
        st = os.stat(path)
        os.chmod(path, st.st_mode | stat.S_IEXEC)
项目:s2e-env    作者:S2E    | 项目源码 | 文件源码
def _download_repo(repo_path):
    """
    Download Google's repo.
    """
    logger.info('Fetching repo')

    repo_url = CONSTANTS['repo']['url']
    response = requests.get(repo_url)

    if response.status_code != 200:
        raise CommandError('Unable to download repo from %s' % repo_url)

    with open(repo_path, 'wb') as f:
        f.write(response.content)

    logger.success('Fetched repo')

    # Ensure that the repo binary is executable
    st = os.stat(repo_path)
    os.chmod(repo_path, st.st_mode | stat.S_IEXEC)
项目:conda-shell    作者:gbrener    | 项目源码 | 文件源码
def test_in_shebang(self, remove_shell_envs, capfd):
        """Test that conda-shell works from within a shebang line."""
        tempfd = tempfile.NamedTemporaryFile(mode='w', delete=False)
        tempfd.write('''#!/usr/bin/env conda-shell
#!conda-shell -i python python=3.6 numpy=1.12

import numpy as np
print(f\'np.arange(10): {np.arange(10)}\')
''')
        tempfd.flush()
        tempfd.close()
        stats = os.stat(tempfd.name)
        os.chmod(tempfd.name, stats.st_mode | stat.S_IEXEC)
        subprocess.check_call([tempfd.name],
                              universal_newlines=True,
                              env=remove_shell_envs)
        out, err = capfd.readouterr()
        assert 'np.arange(10): [0 1 2 3 4 5 6 7 8 9]' in out+err
项目:conda-shell    作者:gbrener    | 项目源码 | 文件源码
def test_in_shebang_multiline(self, remove_shell_envs, capfd):
        """Test that conda-shell works from within a shebang line."""
        tempfd = tempfile.NamedTemporaryFile(mode='w', delete=False)
        tempfd.write('''#!/usr/bin/env conda-shell
#!conda-shell -i python python=3.6 numpy=1.12
#!conda-shell -c conda-forge pandas pydap

import numpy as np
import pandas as pd
import pydap

print(f\'np.arange(10): {np.arange(10)}\')
''')
        tempfd.flush()
        tempfd.close()
        stats = os.stat(tempfd.name)
        os.chmod(tempfd.name, stats.st_mode | stat.S_IEXEC)
        subprocess.check_call([tempfd.name],
                              universal_newlines=True,
                              env=remove_shell_envs)
        out, err = capfd.readouterr()
        assert 'np.arange(10): [0 1 2 3 4 5 6 7 8 9]' in out+err
项目:PyPPL    作者:pwwang    | 项目源码 | 文件源码
def chmodX (thefile):
    """
    Convert script file to executable or add extract shebang to cmd line
    @params:
        `thefile`: the script file
    @returns:
        A list with or without the path of the interpreter as the first element and the script file as the last element
    """
    thefile = path.realpath(thefile)
    ret = [thefile]
    try:
        st = stat (thefile)
        chmod (thefile, st.st_mode | S_IEXEC)
    except Exception as e1:
        try:
            shebang = open (thefile).read().strip().splitlines()[0]
            if not shebang.startswith("#!"): # pragma: no cover
                raise
            ret = shebang[2:].strip().split() + [thefile] # pragma: no cover
        except Exception as e2:
            raise Exception("Cannot change %s as executable or read the shebang from it:\n%s\n%s" % (thefile, e1, e2))
    return ret
项目:reframe    作者:eth-cscs    | 项目源码 | 文件源码
def submit(self):
        # `chmod +x' first, because we will execute the script locally
        os.chmod(self._script_filename,
                 os.stat(self._script_filename).st_mode | stat.S_IEXEC)

        # Run from the absolute path
        self._f_stdout = open(self.stdout, 'w+')
        self._f_stderr = open(self.stderr, 'w+')

        # The new process starts also a new session (session leader), so that
        # we can later kill any other processes that this might spawn by just
        # killing this one.
        self._proc = os_ext.run_command_async(
            os.path.abspath(self._script_filename),
            stdout=self._f_stdout,
            stderr=self._f_stderr,
            start_new_session=True)

        # Update job info
        self._jobid = self._proc.pid
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def execute(self, name, options, parameters):
        try:
            self._cmdLock.acquire()
            self._log.debug("execute(%s, %s, %s)", name, options, parameters)
            if not name.startswith("/"):
                raise CF.InvalidFileName(CF.CF_EINVAL, "Filename must be absolute")

            if self.isLocked(): raise CF.Device.InvalidState("System is locked down")
            if self.isDisabled(): raise CF.Device.InvalidState("System is disabled")

            priority = 0
            stack_size = 4096
            invalidOptions = []
            for option in options:
                val = option.value.value()
                if option.id == CF.ExecutableDevice.PRIORITY_ID:
                    if ((not isinstance(val, int)) and (not isinstance(val, long))):
                        invalidOptions.append(option)
                    else:
                        priority = val
                elif option.id == CF.ExecutableDevice.STACK_SIZE_ID:
                    if ((not isinstance(val, int)) and (not isinstance(val, long))):
                        invalidOptions.append(option)
                    else:
                        stack_size = val
            if len(invalidOptions) > 0:
                self._log.error("execute() received invalid options %s", invalidOptions)
                raise CF.ExecutableDevice.InvalidOptions(invalidOptions)

            command = name[1:] # This is relative to our CWD
            self._log.debug("Running %s %s", command, os.getcwd())

            if not os.path.isfile(command):
                raise CF.InvalidFileName(CF.CF_EINVAL, "File could not be found %s" % command)
            os.chmod(command, os.stat(command)[0] | stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
        finally:
            self._cmdLock.release()

        return self._execute(command, options, parameters)
项目:process-ocean-color    作者:shaief    | 项目源码 | 文件源码
def create_file(filename):
    print(filename)
    template = getattr(templates, filename)
    target_file = os.path.join(target_directory, '{}.bsh'.format(filename))
    with open(target_file, 'w') as f:
        f.write(template.format(**arguments[filename]))
    st = os.stat(target_file)
    os.chmod(target_file, st.st_mode | stat.S_IEXEC)
项目:protofuzz    作者:trailofbits    | 项目源码 | 文件源码
def test_find_protoc(self):
        '''
        Can we can find protoc?
        '''
        binary = os.path.join(self.tempdir, 'protoc')
        with open(binary, 'wb+') as f:
            pass
        mode = os.stat(binary)
        os.chmod(binary, mode.st_mode | stat.S_IEXEC)

        found_binary = pbimport.find_protoc(self.tempdir)
        self.assertEqual(found_binary, binary)
项目:common-utils    作者:mechaphish    | 项目源码 | 文件源码
def find_all_executables(folder):
        """

        :param folder:
        :return:
        """
        executable_flag = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH
        return [f for f in os.listdir(folder) if os.stat(os.path.join(folder, f)).st_mode & executable_flag]
项目:mycroft-light    作者:MatthewScholefield    | 项目源码 | 文件源码
def find_download_exe(self):
        exe_file = join(self.rt.paths.user_config, self.exe_name)
        if exe_file:
            return exe_file
        try:
            if call(self.exe_name + ' < /dev/null', shell=True) == 0:
                return self.exe_name
        except OSError:
            pass

        import platform
        import stat

        def snd_msg(cmd):
            """Send message to faceplate"""
            Popen('echo "' + cmd + '" > /dev/ttyAMA0', shell=True)

        arch = platform.machine()
        exe_file = expanduser('~/.mycroft/precise/' + self.exe_name)
        url = self.url_base + 'dist/' + arch + '/' + self.exe_name

        snd_msg('mouth.text=Updating Listener...')
        self.download(url, exe_file)
        snd_msg('mouth.reset')

        os.chmod(exe_file, os.stat(exe_file).st_mode | stat.S_IEXEC)
        Popen('echo "mouth.reset" > /dev/ttyAMA0', shell=True)
        return exe_file
项目:py-solc    作者:ethereum    | 项目源码 | 文件源码
def chmod_plus_x(executable_path):
    current_st = os.stat(executable_path)
    os.chmod(executable_path, current_st.st_mode | stat.S_IEXEC)
项目:py-solc    作者:ethereum    | 项目源码 | 文件源码
def chmod_plus_x(executable_path):
    current_st = os.stat(executable_path)
    os.chmod(executable_path, current_st.st_mode | stat.S_IEXEC)
项目:kudubot    作者:namboy94    | 项目源码 | 文件源码
def build(service_directory):
    """
    Builds a Service using the service configuration
    inside the service directory.

    :param service_directory: The location of the service directory
    :return: The path to the generated executable file
    """

    service_name = os.path.basename(service_directory)
    current_dir = os.getcwd()
    os.chdir(service_directory)

    with open("service.json", 'r') as f:
        config = json.load(f)

    try:
        Popen(config["build_commands"]).wait()
    except BaseException as e:
        print(e)
        os.chdir(current_dir)
        return

    output = config["output_file"]
    st = os.stat(output)
    os.chmod(output, st.st_mode | stat.S_IEXEC)  # Make executable

    if os.path.basename(output) != service_name:
        new_output = os.path.join(os.path.dirname(output), service_name)
        os.rename(output, new_output)
        output = new_output

    os.chdir(current_dir)

    return os.path.join(service_directory, output)
项目:NordVPN-NetworkManager    作者:Chadsr    | 项目源码 | 文件源码
def make_executable(file_path):
    try:
        if os.path.isfile(file_path):
            st = os.stat(file_path)
            os.chmod(file_path, st.st_mode | stat.S_IEXEC)
            return True

    except Exception as ex:
        logger.error(ex)
        return False
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def get_exe():
    """ Get ffmpeg exe
    """
    # Is the ffmpeg exe overridden?
    exe = os.getenv('IMAGEIO_FFMPEG_EXE', None)
    if exe:  # pragma: no cover
        return exe

    plat = get_platform()

    if plat and plat in FNAME_PER_PLATFORM:
        try:
            exe = get_remote_file('ffmpeg/' + FNAME_PER_PLATFORM[plat])
            os.chmod(exe, os.stat(exe).st_mode | stat.S_IEXEC)  # executable
            return exe
        except InternetNotAllowedError:
            pass  # explicitly disallowed by user
        except OSError as err:  # pragma: no cover
            logging.warning("Warning: could not find imageio's "
                            "ffmpeg executable:\n%s" %
                            str(err))

    # Fallback, let's hope the system has ffmpeg
    return 'ffmpeg'


# Get camera format
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def test_spotty(self, binary_path):
        '''self-test spotty binary'''
        try:
            st = os.stat(binary_path)
            os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
            args = [
                binary_path,
                "-n", "selftest",
                "-x", "--disable-discovery"
            ]
            startupinfo = None
            if os.name == 'nt':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            spotty = subprocess.Popen(
                args,
                startupinfo=startupinfo,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                bufsize=0)
            stdout, stderr = spotty.communicate()
            log_msg(stdout)
            if "ok spotty" in stdout:
                return True
            elif xbmc.getCondVisibility("System.Platform.Windows"):
                log_msg("Unable to initialize spotty binary for playback."
                        "Make sure you have the VC++ 2015 runtime installed.", xbmc.LOGERROR)
        except Exception as exc:
            log_exception(__name__, exc)
        return False
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def get_spotty_binary(self):
        '''find the correct spotty binary belonging to the platform'''
        sp_binary = None
        if xbmc.getCondVisibility("System.Platform.Windows"):
            sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "windows", "spotty.exe")
            self.supports_discovery = False  # The current MDNS implementation cannot be built on Windows
        elif xbmc.getCondVisibility("System.Platform.OSX"):
            # macos binary is x86_64 intel
            sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "darwin", "spotty")
        elif xbmc.getCondVisibility("System.Platform.Linux + !System.Platform.Android"):
            # try to find out the correct architecture by trial and error
            import platform
            architecture = platform.machine()
            log_msg("reported architecture: %s" % architecture)
            if architecture.startswith('AMD64') or architecture.startswith('x86_64'):
                # generic linux x86_64 binary
                sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "x86-linux", "spotty-x86_64")
            else:
                # just try to get the correct binary path if we're unsure about the platform/cpu
                paths = []
                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty-muslhf"))
                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty-hf"))
                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "x86-linux", "spotty"))
                for binary_path in paths:
                    if self.test_spotty(binary_path):
                        sp_binary = binary_path
                        break
        if sp_binary:
            st = os.stat(sp_binary)
            os.chmod(sp_binary, st.st_mode | stat.S_IEXEC)
            log_msg("Architecture detected. Using spotty binary %s" % sp_binary)
        else:
            log_msg("Failed to detect architecture or platform not supported ! Local playback will not be available.")
        return sp_binary
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def overwrite(xxnet_version, xxnet_unzip_path):
    progress["update_status"] = "Over writing"
    try:
        for root, subdirs, files in os.walk(xxnet_unzip_path):
            relate_path = root[len(xxnet_unzip_path)+1:]
            target_relate_path = relate_path
            if sys.platform == 'win32':
                if target_relate_path.startswith("code\\default"):
                    target_relate_path = "code\\" + xxnet_version + relate_path[12:]
            else:
                if target_relate_path.startswith("code/default"):
                    target_relate_path = "code/" + xxnet_version + relate_path[12:]

            for subdir in subdirs:
                if relate_path == "code" and subdir == "default":
                    subdir = xxnet_version

                target_path = os.path.join(top_path, target_relate_path, subdir)
                if not os.path.isdir(target_path):
                    xlog.info("mkdir %s", target_path)
                    os.mkdir(target_path)

            for filename in files:
                src_file = os.path.join(root, filename)
                dst_file = os.path.join(top_path, target_relate_path, filename)
                if not os.path.isfile(dst_file) or hash_file_sum(src_file) != hash_file_sum(dst_file):
                    xlog.info("copy %s => %s", src_file, dst_file)
                    if sys.platform != 'win32' and os.path.isfile(dst_file):
                        st = os.stat(dst_file)
                        shutil.copy(src_file, dst_file)
                        if st.st_mode & stat.S_IEXEC:
                            os.chmod(dst_file, st.st_mode)
                    else:
                        shutil.copy(src_file, dst_file)

    except Exception as e:
        xlog.warn("update over write fail:%r", e)
        progress["update_status"] = "Over write Fail:%r" % e
        raise e
    xlog.info("update file finished.")
项目:q2cli    作者:qiime2    | 项目源码 | 文件源码
def write_bash_completion_script(plugins, path):
    """

    Parameters
    ----------
    plugins : dict
        Decoded JSON object representing CLI state on a per-plugin basis (e.g.
        as returned by `DeploymentCache.plugins`). See note within this
        function for why this parameter is necessary.
    path : str
        Path to write completion script to.

    """
    import os
    import os.path
    import stat
    import textwrap
    from q2cli.__main__ import qiime as root

    # `write_bash_completion_script` is called by `q2cli.cache.DeploymentCache`
    # when it is refreshing its cache. `q2cli.commands.RootCommand` could have
    # already asked for the cache, for example, if the user ran a command and
    # the cache must be refreshed. The bash completion script is generated by
    # traversing the `RootCommand` tree, so there is a cycle when `RootCommand`
    # attempts to access the cache in order to build itself. We work around
    # this by bootstrapping the `RootCommand`'s `._plugins` attribute with the
    # plugin state that has already been loaded by `DeploymentCache`.
    root._plugins = plugins

    cmd_reply = _generate_command_reply(root)
    cmd_reply = textwrap.indent(cmd_reply, '  ')
    completion_script = COMPLETION_SCRIPT_TEMPLATE.format(cmd_reply=cmd_reply)

    with open(path, 'w') as fh:
        fh.write(completion_script)

    # Make bash completion script executable:
    #   http://stackoverflow.com/a/12792002/3776794
    st = os.stat(path)
    os.chmod(path, st.st_mode | stat.S_IEXEC)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def overwrite(xxnet_version, xxnet_unzip_path):
    progress["update_status"] = "Over writing"
    try:
        for root, subdirs, files in os.walk(xxnet_unzip_path):
            relate_path = root[len(xxnet_unzip_path)+1:]
            target_relate_path = relate_path
            if sys.platform == 'win32':
                if target_relate_path.startswith("code\\default"):
                    target_relate_path = "code\\" + xxnet_version + relate_path[12:]
            else:
                if target_relate_path.startswith("code/default"):
                    target_relate_path = "code/" + xxnet_version + relate_path[12:]

            for subdir in subdirs:
                if relate_path == "code" and subdir == "default":
                    subdir = xxnet_version

                target_path = os.path.join(top_path, target_relate_path, subdir)
                if not os.path.isdir(target_path):
                    xlog.info("mkdir %s", target_path)
                    os.mkdir(target_path)

            for filename in files:
                src_file = os.path.join(root, filename)
                dst_file = os.path.join(top_path, target_relate_path, filename)
                if not os.path.isfile(dst_file) or hash_file_sum(src_file) != hash_file_sum(dst_file):
                    xlog.info("copy %s => %s", src_file, dst_file)
                    if sys.platform != 'win32' and os.path.isfile(dst_file):
                        st = os.stat(dst_file)
                        shutil.copy(src_file, dst_file)
                        if st.st_mode & stat.S_IEXEC:
                            os.chmod(dst_file, st.st_mode)
                    else:
                        shutil.copy(src_file, dst_file)

    except Exception as e:
        xlog.warn("update over write fail:%r", e)
        progress["update_status"] = "Over write Fail:%r" % e
        raise e
    xlog.info("update file finished.")
项目:nitro    作者:KVM-VMI    | 项目源码 | 文件源码
def add_file_from_str(self, name, content, executable=False, convert_nl=False, dedent=False):
        path = os.path.join(self.cdrom_dir, name)
        if dedent:
            content = textwrap.dedent(content)
        if convert_nl:
            content = content.replace("\n", "\r\n")
        with open(path, "w") as f:
            f.write(content)
        if executable:
            current = os.stat(path)
            os.chmod(path, current.st_mode | stat.S_IEXEC)
项目:digger-build-cli    作者:aerogear    | 项目源码 | 文件源码
def prepare(self):
    """
    Prepares the android project to the build process.

    Checks if the project uses either gradle or ant and executes the necessary steps.
    """
    self.src_folder = self.get_src_folder()
    st = os.stat('%s/gradlew' % self.path)
    os.chmod('%s/gradlew' % self.path, st.st_mode | stat.S_IEXEC)
项目:SimpleFF    作者:seanyeh    | 项目源码 | 文件源码
def _gen_ffbinary(self, ffname):
        bin_data = pkgutil.get_data("bin", ffname)

        temp = tempfile.NamedTemporaryFile(delete=False)
        temp.write(bin_data)
        temp.close()

        # chmod +x
        os.chmod(temp.name, os.stat(temp.name).st_mode | stat.S_IEXEC)

        return temp
项目:py-geth    作者:ethereum    | 项目源码 | 文件源码
def chmod_plus_x(executable_path):
    current_st = os.stat(executable_path)
    os.chmod(executable_path, current_st.st_mode | stat.S_IEXEC)
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def add_init_script(self, file, name):
        """
        Add this file to the init.d directory
        """
        f_path = os.path.join("/etc/init.d", name)
        f = open(f_path, "w")
        f.write(file)
        f.close()
        os.chmod(f_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
        self.run("/usr/sbin/update-rc.d %s defaults" % name)
项目:nimp    作者:dontnod    | 项目源码 | 文件源码
def _make_executable_if_needed(filename):
        # If this is an executable or a script, make it +x
        if MAGIC is not None:
            filetype = MAGIC.from_file(filename)
            if isinstance(filetype, bytes):
                # Older versions of python-magic return bytes instead of a string
                filetype = filetype.decode('ascii')

            if 'executable' in filetype or 'script' in filetype:
                try:
                    logging.info('Making executable because of file type: %s', filetype)
                    file_stat = os.stat(filename)
                    os.chmod(filename, file_stat.st_mode | stat.S_IEXEC)
                except Exception: #pylint: disable=broad-except
                    pass
项目:imagine    作者:hertogp    | 项目源码 | 文件源码
def image(self, fmt=None):
        '<fname>.shebang [options] <fname>.png'
        os.chmod(self.inpfile, stat.S_IEXEC | os.stat(self.inpfile).st_mode)
        args = self.options + [self.outfile]
        if self.cmd(self.inpfile, *args):
            return self.result()

# use sys.modules[__name__].__doc__ instead of __doc__ directly
# to avoid pylint'rs complaints.
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def create_exe(outpath, c_code=None):
    assert not os.path.exists(outpath), outpath
    if which("gcc"):
        if c_code is None:
            c_code = textwrap.dedent(
                """
                #include <unistd.h>
                int main() {
                    pause();
                    return 1;
                }
                """)
        with tempfile.NamedTemporaryFile(
                suffix='.c', delete=False, mode='wt') as f:
            f.write(c_code)
        try:
            subprocess.check_call(["gcc", f.name, "-o", outpath])
        finally:
            safe_rmpath(f.name)
    else:
        # fallback - use python's executable
        shutil.copyfile(sys.executable, outpath)
        if POSIX:
            st = os.stat(outpath)
            os.chmod(outpath, st.st_mode | stat.S_IEXEC)


# ===================================================================
# --- testing
# ===================================================================
项目:mobileinsight-core    作者:mobile-insight    | 项目源码 | 文件源码
def download_libs(url, libs, chmod = True):
    for lib in libs:
        if not os.path.isfile("./libs/" + lib):
            urllib.urlretrieve (url + lib, "./libs/" + lib)
    if chmod:
        for lib in libs:
            os.chmod("./libs/" + lib, 0o755 | stat.S_IEXEC)
项目:clusterfuzz-tools    作者:google    | 项目源码 | 文件源码
def get_binary_path(self):
    """Return binary path and ensure it's executable."""
    path = os.path.join(self.get_build_dir_path(), self.get_binary_name())
    stats = os.stat(path)
    os.chmod(path, stats.st_mode | stat.S_IEXEC)
    return path
项目:ahenk    作者:Pardus-LiderAhenk    | 项目源码 | 文件源码
def make_executable(full_path):
        try:
            st = os.stat(full_path)
            os.chmod(full_path, st.st_mode | stat.S_IEXEC)
        except:
            raise
项目:andcre    作者:fooock    | 项目源码 | 文件源码
def make_file_executable(file):
    st = os.stat(file)
    os.chmod(file, st.st_mode | stat.S_IEXEC)