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
python类S_IEXEC的实例源码
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
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
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
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.")
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)
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.")
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)
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)
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
def chmod_plus_x(executable_path):
current_st = os.stat(executable_path)
os.chmod(executable_path, current_st.st_mode | stat.S_IEXEC)
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)
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
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.
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
# ===================================================================
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)
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
def make_executable(full_path):
try:
st = os.stat(full_path)
os.chmod(full_path, st.st_mode | stat.S_IEXEC)
except:
raise
def make_file_executable(file):
st = os.stat(file)
os.chmod(file, st.st_mode | stat.S_IEXEC)